1. 程式人生 > >NOI:7062 區間合併

NOI:7062 區間合併

轉載:https://blog.csdn.net/loi_black/article/details/52874488

題目:http://noi.openjudge.cn/ch0204/7620/

Description 
給定 n 個閉區間 [ai; bi],其中i=1,2,…,n。任意兩個相鄰或相交的閉區間可以合併為一個閉區間。例如,[1;2] 和 [2;3] 可以合併為 [1;3],[1;3] 和 [2;4] 可以合併為 [1;4],但是[1;2] 和 [3;4] 不可以合併。

我們的任務是判斷這些區間是否可以最終合併為一個閉區間,如果可以,將這個閉區間輸出,否則輸出no。

Input 
第一行為一個整數n,3 ≤ n ≤ 50000。表示輸入區間的數量。 之後n行,在第i行上(1 ≤ i ≤ n),為兩個整數ai 和 bi ,整數之間用一個空格分隔,表示區間 [ai; bi](其中 1 ≤ ai ≤ bi ≤ 10000)。 
Output 
輸出一行,如果這些區間最終可以合併為一個閉區間,輸出這個閉區間的左右邊界,用單個空格隔開;否則輸出 no。 
Sample Input 

5 6 
1 5 
10 10 
6 9 
8 10 
Sample Output 
1 10

sort後貪心,判斷當前能否更新,能更新就更新,不能就輸出no。

程式碼如下:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int maxn=100005;
struct dqs
{
    int x,y;
}hh[maxn];
bool flag=0;
bool cmp(dqs a,dqs b)
{
    if(a.x==b.x)
        return a.y<b.y;
    return
a.x<b.x; } int main() { int ans=1; int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d%d",&hh[i].x,&hh[i].y); sort(hh+1,hh+n+1,cmp); int l=hh[1].x,r=hh[1].y; for(int i=2;i<=n;i++) { if(hh[i].x<=r) { if(hh[i].y>r) r=hh[i].y; } else
{ printf("no\n"); flag=1; break; } } if(flag==0) printf("%d %d",l,r); return 0; }