Problem H: 周老师的区间问题
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1034 Solved: 132
Description
周老师无聊时乱写了 n 个区间,但处女座的他随后又想将 n 个区间整理合并,但他发现区间太多了,于是他想请你帮帮他
Input
每次测试输入多组数据(小于100组),对于每组输入数据:
第一行为 n ,代表 n 个区间
接下来 n 行,每行两个数 s , t 代表区间 [s,t]
0 < n < 15000
0 <= s <= t < 10000000
Output
第一行输出一个数字 q ,代表合并后剩余的区间个数
随后 q 行 按从小到大的顺序输出区间
Sample Input
3
2 4
1 3
7 7
Sample Output
2
1 4
7 7
HINT
思路:
简单的贪心问题,就是按区间左边的大小进行升序排序,注意别忘了判断的时候考虑包含的情况,自己一直没考虑,错了好几发
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#define ll long long
using namespace std;
struct Node{
ll x;
ll y;
}node[15005];
bool cmp(Node a,Node b){
if(a.x!=b.x)
return a.x<b.x;
return a.y<b.y;
}
Node q[15005];
ll ans;
int main(){
ll n;
while(cin>>n){
ans=0;
for(ll i=1;i<=n;i++)
cin>>node[i].x>>node[i].y;
sort(node+1,node+n+1,cmp);
q[++ans].x=node[1].x;
q[ans].y=node[1].y;
for(ll i=2;i<=n;i++){
if(q[ans].y>=node[i].x&&node[i].y>=q[ans].y){
q[ans].y=node[i].y;
}
else if(q[ans].y>=node[i].y&&q[ans].x<=node[i].x){ //别忘了考虑包含情况。。。
continue;
}
else if(q[ans].y<node[i].x){
ans++;
q[ans].x=node[i].x;
q[ans].y=node[i].y;
}
}
cout<<ans<<endl;
for(ll i=1;i<=ans;i++)
cout<<q[i].x<<" "<<q[i].y<<endl;
}
return 0;
}