1991Segments

Segments

Time Limit: 1 Seconds     Memory Limit: 32768 K

Total Submit:111     Accepted:34


Description

You are to find the total length of union of n segments located on a horizontal line.

Input

The input consists of T test cases. The first line contains a positive integer T which is the number of test cases you will solve. Following are input data for T cases. The first number in each test case is an integer n (1 ≤ n ≤ 5000) representing the number of segments. Following are 2n intergers (L1 R1,L2 R2,…,and Li≤Ri), in which each pair of interges [Li,Ri] defines the range of the ith segment on the horizontal line. All integers do not exceed 109 by an absolute value.

Output

For each test case, print only one number in a line, denotes the total length of union of given segments.

Sample Input

2
3
0 5
3 6
7 8
3
-1000000000 1000000000
-1000 1000
1 100 

 

Sample Output

7
2000000000

Source:

#include<iostream.h>
int main()
{
	int t,n,i,j,k,mx,my,sum;
	long a[5001][2],b[5001][2];
	cin>>t;
	while(t--)
	{
		cin>>n;
		for(i=1;i<=n;i++)
			cin>>a[i][0]>>a[i][1];
		for(i=1;i<n;i++)
		{
			k=i;
			for(j=i+1;j<=n;j++)
				if(a[k][0]>a[j][0])
					k=j;
			if(k!=i)
			{
			   mx=a[i][0];
			   my=a[i][1];
			   a[i][0]=a[k][0];
			   a[i][1]=a[k][1];
			   a[k][0]=mx;
			   a[k][1]=my;
			}
		}
		b[1][0]=a[1][0];
		b[1][1]=a[1][1];
		j=1;
		for(i=2;i<=n;i++)
		{
			if(a[i][0]<=b[j][1])
			{
				if(b[j][1]<a[i][1])
					b[j][1]=a[i][1];
			}
			else
			{
				j++;
				b[j][0]=a[i][0];
				b[j][1]=a[i][1];
			}
		}
		sum=0;
		for(i=1;i<=j;i++)
			sum=sum+b[i][1]-b[i][0];

	  cout<<sum<<endl;
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值