1214 线段覆盖
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 黄金 Gold
题目描述 Description
给定x轴上的N(0<N<100)条线段,每个线段由它的二个端点a_I和b_I确定,I=1,2,……N.这些坐标都是区间(-999,999)的整数。有些线段之间会相互交叠或覆盖。请你编写一个程序,从给出的线段中去掉尽量少的线段,使得剩下的线段两两之间没有内部公共点。所谓的内部公共点是指一个点同时属于两条线段且至少在其中一条线段的内部(即除去端点的部分)。
输入描述 Input Description
输入第一行是一个整数N。接下来有N行,每行有二个空格隔开的整数,表示一条线段的二个端点的坐标。
输出描述 Output Description
输出第一行是一个整数表示最多剩下的线段数。
样例输入 Sample Input
3
6 3
1 3
2 5
样例输出 Sample Output
2
数据范围及提示 Data Size & Hint
0<N<100
先对线段的右端点排序,然后从最左边开始扫就好了。
Code:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct number
{
int x,y;
};
int cmp(number a,number b)
{
return a.x < b.x;
}
int main()
{
int n,x,y;
scanf("%d",&n);
{
number num[110];
memset(num,0,sizeof(num));
for(int i = 0; i < n; i++)
{
scanf("%d%d",&x,&y);
if(y < x){
num[i].x = y;
num[i].y = x;}
else{
num[i].x = x;
num[i].y = y;
}
}
sort(num,num+n,cmp);
int t = n;
number tmp = num[0];
for(int i = 1; i < n; i++)
{
if(tmp.x <= num[i].x && tmp.y >= num[i].y)
{
t--;
tmp = num[i];
}
else if(num[i].x < tmp.y && num[i].y > tmp.y)
{
t--;
}
else tmp=num[i];
}
printf("%d\n",t);
}
return 0;
}