贪心+区间合并POJ 1089

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了贪心+区间合并POJ 1089相关的知识,希望对你有一定的参考价值。

Intervals
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 8270   Accepted: 3268

Description

There is given the series of n closed intervals [ai; bi], where i=1,2,...,n. The sum of those intervals may be represented as a sum of closed pairwise non?intersecting intervals. The task is to find such representation with the minimal number of intervals. The intervals of this representation should be written in the output file in acceding order. We say that the intervals [a; b] and [c; d] are in ascending order if, and only if a <= b < c <= d. 
Task 
Write a program which: 
reads from the std input the description of the series of intervals, 
computes pairwise non?intersecting intervals satisfying the conditions given above, 
writes the computed intervals in ascending order into std output

Input

In the first line of input there is one integer n, 3 <= n <= 50000. This is the number of intervals. In the (i+1)?st line, 1 <= i <= n, there is a description of the interval [ai; bi] in the form of two integers ai and bi separated by a single space, which are respectively the beginning and the end of the interval,1 <= ai <= bi <= 1000000.

Output

The output should contain descriptions of all computed pairwise non?intersecting intervals. In each line should be written a description of one interval. It should be composed of two integers, separated by a single space, the beginning and the end of the interval respectively. The intervals should be written into the output in ascending order.

Sample Input

5
5 6
1 4
10 10
6 9
8 10

Sample Output

1 4
5 10

题目大意:
合并n个区间。。(为什么我看学长们写的题目大意都那么长==)

题解:
贪心思想,排个序再合并即可。
按照左端排序,能合并就合并,
不能合并则前面的区间一定不能被后面的合并,输出前面的区间。

代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct data{int a,b;}set[50001];
bool cmp(data x,data y) {return x.a<y.a;} //按左端点排序
inline int read(){
    int x=0,f=1;
    char c=getchar();
    for(;!isdigit(c);c=getchar())
        if(c==-)
            f=-1;
    for(;isdigit(c);c=getchar())
        x=x*10+c-0;
    return x*f;
}
int main(){
    int N=read();
    for(int i=1;i<=N;i++)
        set[i].a=read(), set[i].b=read();
    sort(set+1,set+1+N,cmp);
    int left=set[1].a, right=set[1].b; //判断能否合并的参照值
    for(int i=1;i<=N;i++){
        //可以合并
        if(set[i].a>=left && set[i].a<=right){ 
            if(set[i].b>right)    
                right=set[i].b;
        } 
       //不可合并
        else{
            printf("%d %d\n",left,right); //输出
            //修改参照值
            left=set[i].a;
            right=set[i].b;     
        } 
    }
    printf("%d %d\n",left,right);
    //system("pause");
    return 0;
}

 

 

以上是关于贪心+区间合并POJ 1089的主要内容,如果未能解决你的问题,请参考以下文章

贪心算法----区间覆盖问题(POJ2376)

POJ 1089 Intervals

ACM - 贪心(经典母题+POJ一些练习题)

ACM - 贪心(经典母题+POJ一些练习题)

ACM - 贪心(经典母题+POJ一些练习题)

ACM - 贪心(经典母题+POJ一些练习题)