7620:区间合并
-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
给定 n 个闭区间 [ai; bi],其中i=1,2,...,n。任意两个相邻或相交的闭区间可以合并为一个闭区间。例如,[1;2] 和 [2;3] 可以合并为 [1;3],[1;3] 和 [2;4] 可以合并为 [1;4],但是[1;2] 和 [3;4] 不可以合并。
我们的任务是判断这些区间是否可以最终合并为一个闭区间,如果可以,将这个闭区间输出,否则输出no。
输入
-
第一行为一个整数n,3 ≤ n ≤ 50000。表示输入区间的数量。
之后n行,在第i行上(1 ≤ i ≤ n),为两个整数 ai 和 bi ,整数之间用一个空格分隔,表示区间 [ai; bi](其中 1 ≤ ai ≤ bi ≤ 10000)。
输出
- 输出一行,如果这些区间最终可以合并为一个闭区间,输出这个闭区间的左右边界,用单个空格隔开;否则输出 no。 样例输入
-
5 5 6 1 5 10 10 6 9 8 10
样例输出
-
1 10
来源
- 习题(14-8)
#include <stdio.h>
#include <iostream>
#include <stack>
#include <string.h>
#include <queue>
#include <math.h>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <iomanip>
using namespace std;
typedef long long LL;
#define MAX 1000001
//int a[MAX][MAX];
//int b[MAX][MAX];
//int res[MAX][MAX];
char c1[200];
char c2[200];
struct Node{
int x;
int y;
};
bool cmp(Node a, Node b){
if(a.x == b.x){
return a.y < b.y;
}
return a.x < b.x;
}
//这个是 有点像贪心算法?
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n;
cin >> n;
Node node[50001];
for(int i = 0; i < n; i++){
cin >> node[i].x >> node[i].y;
}
sort(node, node + n, cmp); //先排序
int begin = node[0].x; //记第一个起始位置和结束位置
int end = node[0].y;
for(int i = 1; i < n; i++){
if(node[i].x <= end){ //如果后一个的结点的第一个值 没有比 前一个结点的第二个值大的话 说明是可以连接在一起的
if(node[i].y > end){ //如果第二个结点 的 第二个值 比 之前第一个结点的 第二个值 大的话 记得更新值
end = node[i].y;
}
}else {
cout << "no" << endl; //否则 是连不到一起
return 0;
}
}
cout << begin << " " << end << endl;;
return 0;
}