CodeForces 85D Sum of Medians (线段树)

题意:给你3种操作:1. 向集合中加入数x。2.在集合中删除数x。3.求和sum:  将集合中的数组排好序,将下标(从1开始) 对5取模为3 的位置的数求和。

析:利用线段树维护6个值,首先是1-5表示每五个一组的和,然后还有要维护一个该字段的长度,因为其中有删除和增加操作,还有我们要对原数据进行离散化,

因为要保证有顺序,每次输出都是第三个元素。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e16;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e5 + 10;
const int mod = 1000000007;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r >= 0 && r < n && c >= 0 && c < m;
}

struct Node{
  int op, val;
  Node(int o = 0, int v = 0) : op(o), val(v) { }
};
vector<int> num;
Node a[maxn];
LL sum[maxn<<2][6];

void push_up(int rt){
  int l = rt<<1, r = rt<<1|1;
  for(int i = 0; i < 5; ++i)
    sum[rt][i] = sum[l][i] + sum[r][((i-sum[l][5])%5+5)%5];
  sum[rt][5] = sum[l][5] + sum[r][5];
}

void build(int l, int r, int rt){
  sum[rt][5] = r - l + 1;
  if(l == r)  return ;
  int m = l + r >> 1;
  build(lson);
  build(rson);
}

void update(int M, int op, int val, int l, int r, int rt){
  if(l == r){
    sum[rt][5] += op;
    sum[rt][0] += val;
    return ;
  }
  int m = l + r >> 1;
  if(M <= m)  update(M, op, val, lson);
  else  update(M, op, val, rson);
  push_up(rt);
}

int main(){
  scanf("%d", &n);
  char s[10];
  for(int i = 0; i < n; ++i){
    scanf("%s", s);
    if(s[0] == 's')  continue;
    int x;
    scanf("%d", &x);
    a[i] = Node(s[0] == 'a' ? 1 : -1, x);
    num.push_back(x);
  }
  sort(num.begin(), num.end());
  num.erase(unique(num.begin(), num.end()), num.end());
  for(int i = 0; i < n; ++i){
    if(a[i].op == 0){  printf("%I64d
", sum[1][2]);  continue; }
    int t = lower_bound(num.begin(), num.end(), a[i].val)  - num.begin() + 1;
    update(t, a[i].op, a[i].val * a[i].op, 1, num.size(), 1);
  }
  return 0;
}

  

原文地址:https://www.cnblogs.com/dwtfukgv/p/7125356.html