Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.
Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of segments drawn by Vika.
Each of the next n lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.
Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.
3
0 1 2 1
1 4 1 2
0 3 2 3
8
4
-2 -1 2 -1
2 1 -2 1
-1 -2 -1 2
1 2 1 -2
16
In the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).
题意:在坐标系上画n条线段,求经过了多少个点?
题解:我们把右上角的坐标都加1转换为求面积。用扫描线。下面这篇博客可以http://blog.csdn.net/harlow_cheng/article/details/53027415
1 #include<iostream> 2 #include<cstdio> 3 #include<vector> 4 #include<cstring> 5 #include<algorithm> 6 #define pii pair<int,int> 7 #define ll long long 8 #define pb push_back 9 #define mp make_pair 10 using namespace std; 11 const int maxn=1e5+10; 12 int sum[maxn<<3]; 13 vector<int>a; 14 int cnt[maxn<<3],n; 15 struct node 16 { 17 int x1,x2,h,k; 18 bool operator<(const node b)const 19 { 20 return h<b.h; 21 } 22 }bian[maxn<<1+5]; 23 24 void push_up(int rt,int l,int r) 25 { 26 if(cnt[rt]) 27 sum[rt]=a[r+1]-a[l]; 28 else 29 if(l==r) 30 sum[rt]=0; 31 else 32 sum[rt]=sum[rt<<1]+sum[rt<<1|1]; 33 } 34 void update(int L,int R,int c,int l,int r,int rt) 35 { 36 if(L<=l&&r<=R) 37 { 38 cnt[rt]+=c; 39 push_up(rt,l,r); 40 return; 41 } 42 int m=(l+r)>>1; 43 if(L<=m)update(L,R,c,l,m,rt<<1); 44 if(m<R)update(L,R,c,m+1,r,rt<<1|1); 45 push_up(rt,l,r); 46 } 47 int main() 48 { 49 scanf("%d",&n); 50 int num=0; 51 for(int i=0;i<n;i++) 52 { 53 int x1,x2,y1,y2; 54 scanf("%d %d %d %d",&x1,&y1,&x2,&y2); 55 if(x1>x2)swap(x1,x2); 56 if(y1>y2)swap(y1,y2); 57 x2++;y2++; 58 a.pb(x1);a.pb(x2); 59 num++; 60 bian[num].x1=x1;bian[num].x2=x2;bian[num].h=y1;bian[num].k=1; 61 num++; 62 bian[num].x1=x1;bian[num].x2=x2;bian[num].h=y2;bian[num].k=-1; 63 } 64 sort(a.begin(),a.end()); 65 a.erase(unique(a.begin(),a.end()),a.end()); 66 sort(bian+1,bian+1+num); 67 ll ans=0; 68 for(int i=1;i<=num-1;i++) 69 { 70 int l=lower_bound(a.begin(),a.end(),bian[i].x1)-a.begin(); 71 int r=lower_bound(a.begin(),a.end(),bian[i].x2)-a.begin()-1; 72 update(l,r,bian[i].k,0,a.size()-1,1); 73 ans+=(ll)sum[1]*(bian[i+1].h-bian[i].h); 74 } 75 printf("%I64d ",ans); 76 return 0; 77 }