Advertisement
Guest User

Solution for spoj.pl/problems/INTEST/

a guest
Jun 28th, 2010
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <algorithm>
  2. #include <numeric>
  3. #include <iostream>
  4. #include <vector>
  5. #include <map>
  6. using namespace std;
  7.  
  8. struct brick{
  9.     int x1,x2,y1,y2,id;
  10.     brick(int x1, int y1, int x2, int y2, int id):x1(x1),y1(y1),x2(x2),y2(y2),id(id){}
  11.     brick():id(-1){}
  12. };
  13.  
  14. bool by_x(const brick& a, const brick& b){
  15.     return a.x1 < b.x1;
  16. }
  17.  
  18. bool by_y(const brick& a, const brick& b){
  19.     if (a.y2 != b.y2) return a.y2<b.y2;
  20.     else return a.x1<b.x1;
  21. }
  22.  
  23. map<int, vector<brick> > h;
  24. brick bricks[100005];
  25.  
  26. int p[100005], rk[100005];
  27.  
  28. int getp(int u){
  29.     if (p[u] != u) p[u]=getp(p[u]);
  30.     return p[u];
  31. }
  32.  
  33. bool merge(int u, int v){
  34.     int pu=getp(u), pv=getp(v);
  35.     if (pu == pv) return false;
  36.     if (rk[pu] < rk[pv]){
  37.         p[pu]=pv;
  38.     } else {
  39.         p[pv]=pu;
  40.         if (rk[pu] == rk[pv]) ++rk[pu];
  41.     }
  42.     return true;
  43. }
  44.  
  45. int main() {
  46.     int n;
  47.     scanf("%d",&n);
  48.     for(int i=0; i<n; ++i){
  49.         rk[i]=1; p[i]=i;
  50.         int x1, x2, y1, y2;
  51.         scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
  52.         if (x1>x2) swap(x1,x2); if (y1>y2) swap(y1,y2);
  53.         bricks[i] = brick(x1,y1,x2,y2,i);
  54.         h[y2].push_back(bricks[i]);
  55.     }
  56.     for(map<int,vector<brick> >::iterator it=h.begin(); it != h.end(); ++it) sort(it->second.begin(),it->second.end(),by_x);
  57.     sort(bricks,bricks+n,by_y);
  58.     int res=n;
  59.  
  60.     for(int i=0; i<n; ++i){
  61.         vector<brick> &v = h[bricks[i].y1];
  62.         if (v.size() == 0) continue;
  63.         int sz = v.size();
  64.         if (v[0].x1 >= bricks[i].x2 || v[sz-1].x2 <= bricks[i].x1) continue;
  65.         int L = 0;
  66.         if (v[0].x2 <= bricks[i].x1){
  67.             int r=sz-1;
  68.             while (L+1<r){
  69.                 int m=(L+r)/2;
  70.                 if (v[m].x2 <= bricks[i].x1) L=m; else r=m;
  71.             }
  72.             L=r;
  73.         }
  74.         int R = sz-1;
  75.         if (v[R].x1 >= bricks[i].x2){
  76.             int l=0;
  77.             while (l+1<R){
  78.                 int m=(l+R)/2;
  79.                 if (v[m].x1 >= bricks[i].x2) R=m; else l=m;
  80.             }
  81.             R=l;
  82.         }
  83.         for (int j=L; j<=R; ++j) if (merge(bricks[i].id,v[j].id)) --res;
  84.     }
  85.     printf("%d",res);
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement