C
来源:互联网 发布:辣酱油 知乎 编辑:程序博客网 时间:2024/05/18 12:39
C - sui题/经典问题
You are given two interval collections A and B. Collection A has N intervals [ A1, A2 ], [ A3, A4 ], …, [ A2N-1, A2N ] and collection B has M intervals [ B1, B2 ], [ B3, B4 ], …, [ B2M-1, B2M ]. Your task is to calculate the length of A - B.
For example if A = {[2, 5], [4, 10], [14, 18]} and B = {[1, 3], [8, 15]}, the length of A - B ({(3, 8), (15, 18]}) is 8.
Input
Line 1: Two integers N and M (1 ≤ N, M ≤ 100000).
Line 2: 2*N integers, A1, A2, …, A2N (1 ≤ Ai ≤ 100000000).
Line 3: 2*M integers, B1, B2, …, B2M (1 ≤= Bi ≤ 100000000).
Output
The length of A - B.
Sample Input
3 2
2 5 4 10 14 18
1 3 8 15
Sample Output
8
我又写了一份毒代码,能够感觉感觉思路是对,但就是wa,调试了好久才发现最后区间减的时候有两种情况没考虑进去,哎,水平没达到,希望自己和别人少犯这种错误。
思路:先对区间排序,之后对区间合并,最后相减。
#include <iostream>#include <cstdio>#include <algorithm>using namespace std;const int N = 100050;int n,m;struct node{ int a, b;}s1[N],s2[N];bool cmp(node a,node b){ return a.a<b.a||a.a==b.a&&a.b<b.b;}int flow(node *p,int h,int g){ int a=1,c=g; for(int i=2;i<=g;i++) { if(p[a].b>=p[i].a){ c--; p[a].b=max(p[i].b,p[a].b); } else { a++; p[a].a=p[i].a;p[a].b=p[i].b; } } return c;}int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n>>m;int a,b; int ans=0; for(int i=1;i<=n;i++) { cin>>a>>b;s1[i].a=a,s1[i].b=b; } for(int i=1;i<=m;i++) { cin>>a>>b;s2[i].a=a;s2[i].b=b; } sort(s1+1,s1+n+1,cmp); sort(s2+1,s2+m+1,cmp); n=flow(s1,1,n); m=flow(s2,1,m); int f,g=1;int k=1; for(int i=1;i<=n;i++) { int f=s1[i].a; while(g<=m) { if(s2[g].b>=f) break; g++; } if(g>m){ while(i<=n) { ans+=s1[i].b-s1[i].a; i++; } break; } a=s2[g].a; ans+=min(max(0,a-f),s1[i].b-f); b=s1[i].b; while(g+1<=m&&s2[g+1].a<b) { ans+=s2[g+1].a-s2[g].b; g++; } if(s2[g].b<b) ans+=b-s2[g].b; } cout<<ans<<endl; return 0;}