Codeforces 19D Points(树状数组)

2015-01-27 18:05:32 · 作者: · 浏览: 51

题目链接:Codeforces 19D Points

题目大意:N中操作,每次添加一个点,或者删除一个点,以及找到给定x,y坐标最近的一个坐标,并且保证xi,yi在x,y的右上角。

解题思路:这题的解法还是很机智的。

y坐标离散化,然后树状数组的每个单位用一个set代替,set记录的是点集。

剩下的操作就像树状数组一样,每次添加就等于是+w的操作,移除就等于是-w,只是w是一个点,那么find操作就等于是在sum操作生成的点集中二分查找。

#include 
   
     #include 
    
      #include 
     
       #include
       #include 
       
         #include 
        
          using namespace std; const int maxn = 2 * 1e5 + 5; const int INF = 0x3f3f3f3f; #define lowbit(x) ((x)&(-x)) typedef pair
         
           pii; typedef set
          
           ::iterator iter; int N, M, pos[maxn]; set
           
             fenw[maxn]; struct Camd { int x, y; char op[10]; void read() { scanf("%s%d%d", op, &x, &y); } void add() { for (int i = maxn - y; i < maxn; i += lowbit(i)) fenw[i].insert(make_pair(x, y)); } void del() { for (int i = maxn - y; i < maxn; i += lowbit(i)) fenw[i].erase(make_pair(x, y)); } void find() { pii ans(INF, INF); for (int i = maxn-y-1; i; i -= lowbit(i)) { iter it = fenw[i].lower_bound(make_pair(x+1, y)); if (it != fenw[i].end()) ans = min(ans, *it); } if (ans == make_pair(INF,INF)) printf("-1\n"); else printf("%d %d\n", ans.first, pos[ans.second]); } void solve() { if (op[0] == 'a') add(); else if (op[0] == 'r') del(); else find(); } }p[maxn]; void init () { M = 0; scanf("%d", &N); for (int i = 1; i <= N; i++) { p[i].read(); pos[i] = p[i].y; } sort(pos + 1, pos + 1 + N); M = unique(pos+1, pos+1+N) - (pos+1); for (int i = 1; i <= N; i++) p[i].y = lower_bound(pos+1, pos+1+M, p[i].y) - pos; } int main () { init(); for (int i = 1; i <= N; i++) p[i].solve(); return 0; }