SDNU 1310.Cover Interval 区间合并之后求覆盖的区间长度


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.


Input

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.


Output

For each test cases, output one Integer representing the total length.


Sample Input

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;
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值