Description
给定n个开区间,合并他们中的重合者,输出合并后的区间数量。
Input
第一行:n(1 <= n <= 1000)
第2至第n+1行:每行两个整数(不会超过int),第i行的两个整数表示第i-1个区间的左边界和右边界。
Output
合并后所剩余的区间数量。
Sample Input
3
1 3
2 5
6 7
Sample Output
2
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstring>
using namespace std;
struct shu
//定义一个结构体
{
int a,b;
} p[1010];
bool cmp(shu aaa, shu bbb)
//将sort按a从小到大的顺序排序
{
if(aaa.a!=bbb.a)
return aaa.a<
bbb.a;
}
int main()
{
int n,t;
scanf("%d", &
n);
t=
n;
for(
int i=
0; i<n; i++
)
{
scanf("%d %d", &p[i].a,&
p[i].b);
}
sort(p,p+
n,cmp);
for(
int i=
0; i<n-
1; i++
)
{
//比较第一个的结尾和下一个的开始的大小,看是否区间重复
if(p[i+
1].a<
p[i].b)
{
t--
;
if(p[i+
1].b<
p[i].b)
p[i+
1].b=
p[i].b;
}
}
printf("%d", t);
return 0;
}
转载于:https://www.cnblogs.com/RootVount/p/10381391.html
相关资源:JAVA上百实例源码以及开源项目