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