Description
给定n个开区间,合并他们中的重合者,输出合并后的区间数量。
Input
第一行:n(1 <= n <= 1000)
第2至第n+1行:每行两个整数,第i行的两个整数表示第i-1个区间的左边界和右边界。
Output
合并后所剩余的区间数量。
Sample Input
3
1 3
2 5
6 7
Sample Output
2
#include <stdio.h>
struct NODE{
int left,right;
int father;
}node[1010];
bool Judge(int a, int b){
if(node[b].left >= node[a].right || node[b].right <= node[a].left){
return false;
}
else return true;
}
void Union(int a, int b){
int af = a;
int bf = b;
while(node[af].father != af) af = node[af].father;
while(node[bf].father != bf) bf = node[bf].father;
if(af < bf){
node[bf].father = af;
}
else if(bf < af){
node[af].father = bf;
}
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d%d",&node[i].left, &node[i].right);
node[i].father = i;
}
for(int i=0;i<n-1;i++){
for(int k=i+1;k<n;k++){
if(Judge(i,k)){
Union(i,k);
}
}
}
int sum = 0;
for(int i=0;i<n;i++){
if(node[i].father == i) sum++;
}
printf("%d\n",sum);
return 0;
}