题目大意:两张一样长的纸,每个破损程度不一样。给出破损区间,将两张纸进行合并。求最大连续破损的区间长度为多少?
解题思路:将破损区间Hash为对应的下标值,并对每一个点进行计数标记。然后进行一次扫描。如果出现一次则加加,否则更新最大值以及计数器置0,进行下一个区间进行判断即可。注意有一个陷阱是最后终点要单独进行一次更新,防止没有跳出循环没有对边界值进行更新。详见code。
题目来源:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3518
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e7;
int l,n,m,ans,tmp,a,b;
int h[MAXN];
int main(){
while(~scanf("%d%d%d",&l,&n,&m)){
memset(h,0,sizeof(h));
ans=0;tmp=0;
for(int i=0;i<n;++i){ //接收第一张并Hash
scanf("%d%d",&a,&b);
for(int j=a;j<=b;++j)
h[j]++;
}
for(int i=0;i<m;++i){ //接收第二张并Hash
scanf("%d%d",&a,&b);
for(int j=a;j<=b;++j)
h[j]++;
}
for(int i=0;i<=l;++i){ //扫描计数
if(i==l) ans=max(ans,tmp);
if(h[i]==1) ++tmp; //出现一次则++
else{ //否则记录最大值,更新计数器
ans=max(ans,tmp);
tmp=0;
}
}
printf("%d\n",ans);
}
return 0;
}