题目描述:
给定x轴上的N(0<N<100)条线段,每个线段由它的二个端点a_I和b_I确定,I=1,2,……N.这些坐标都是区间(-999,999)的整数。有些线段之间会相互交叠或覆盖。请你编写一个程序,从给出的线段中去掉尽量少的线段,使得剩下的线段两两之间没有内部公共点。所谓的内部公共点是指一个点同时属于两条线段且至少在其中一条线段的内部(即除去端点的部分)。
输入描述:
输入第一行是一个整数N。接下来有N行,每行有二个空格隔开的整数,表示一条线段的二个端点的坐标。
输出描述:
输出第一行是一个整数表示最多剩下的线段数。
样例输入:
3
6 3
1 3
2 5
样例输出:
2
题目解析:
给线段头进行排序,如果线段头相等,则扔掉长的(即长的在后面);但需要考虑一个线段给另一个线段包含的情况;
/*
作者:时光机
题目:p1214 线段覆盖
*/
#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
struct Shiguangji
{
int head;
int tail;
};
bool cmp(Shiguangji A, Shiguangji B)
{
if (A.head == B.head)
return A.tail < B.tail;
if (A.head <= B.head && A.tail >= B.tail)//如果B给A包围了,要B
return false;
if (A.head >= B.head && A.tail <= B.tail)
return true;
return A.head < B.head;
}
int main()
{
Shiguangji S[100];
int n, cnt=1, pos=0, a, b;
cin >> n;
if (n == 0)
{
cout << 0 << endl;
return 0;
}
for (int i = 0; i < n; i++)
{
cin >> a >> b;
S[i].head = a < b ? a : b;
S[i].tail = a > b ? a : b;
}
sort(S, S + n, cmp);
for (int i = 1; i < n; i++)
{
if (S[i].head >= S[pos].tail){
pos = i;
cnt++;
}
}
cout << cnt << endl;
return 0;
}