1310.Cover Interval
Description
On the math class, Teacher Young want to know some of students’ ability of programming, so he write a simple problem on the blackboard:
“There are several integer intervals [a , b] on the x-axis, and a is smaller than b, please compute the total length covered by these intervals.
The input has multiple test cases. Each case begins with a line contains one integer N(1<=N<=100000), which is the number of the intervals. Then comes N lines, each line has two integers, A and B(separated by a space,0<=A<B<=1000000000), which are the left edge and right edge of the interval.
For each test cases, output one Integer representing the total length.
3
2 5
1 4
7 8
Sample Output
5
区间合并问题,当时做这个题的时候还是第一次接触区间合并,现在看看这个方法存在着一定的缺陷,因为太大的数是存不进去的,还好数据比较水AC了,不过还是贴一下这个方法吧。用一个数来储存位置,前面是左端,后面是右端,需要比较的时候再拆分开。这样做主要是排序的时候比较方便处理,问题就是数太大了就没办法了,下面代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
long long mo=1000000000;
long long p[100005],t;
int main()
{
int i;
long long x,y;
long long ans;
while(scanf("%d",&n)!=EOF)
{
memset(p,0,sizeof(p));
ans=0;
for(i=0;i<n;i++)
{
scanf("%lld",&t);
p[i]=t*mo;
scanf("%lld",&t);
p[i]=p[i]+t;
//cout<<"p["<<i<<"] = "<<p[i]<<endl;
}
sort(p,p+n);
x=p[0]/mo;
y=p[0]%mo;
//cout<<"进循环前 x = "<<x<<" y = "<<y<<endl;
for(i=1;i<n;i++)
{
if(y<p[i]/mo)
{
ans=ans+y-x;
//cout<<x<<' '<<y<<endl;
x=p[i]/mo;
y=p[i]%mo;
}
else if(y<p[i]%mo)
y=p[i]%mo;
}
ans=ans+y-x;
cout<<ans<<endl;
//cout<<x<<' '<<y<<endl;
}
return 0;
}