首页 > 代码库 > 1089 Intervals

1089 Intervals

开始前先讲几句废话:这个题我开始也没看懂,后来借助百度翻译,明白了大概是什么意思。 
试题描述 
输入一个n,然后输入n组数据,每个数据有两个数,代表这个闭区间是从几到几。然后看,如果任意两个闭区间有相重的地方,那么就把这两个闭区间合并,最后输出没有合并的闭区间。 
试题描述正版 
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 
输入 
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. 
输出 
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. 
输入示例 

5 6 
1 4 
10 10 
6 9 
8 10 
输出示例 
1 4 
5 10 
解题思路 
这是一道贪心,大概就是把每个闭区间的开始的数排序,然后从小开始,如果这个开始数最小的区间的最后一个数比第二小的区间的第一个数大,那么就将这两个区间合并,如果比它小就将已有的区间输出,以此类推。

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
struct node
{
    int head,tail;
}input[1000010];
bool maxn(node a,node b)
{
    return a.head<b.head;
}
int main()
{
     int n;
     cin>>n;
     for(int i=0;i<n;i++)
         cin>>input[i].head>>input[i].tail;
     sort(input,input+n,maxn);
     int shead=input[0].head,stail=input[0].tail;
     for(int i=1;i<n;i++)
     {
         if(input[i].head>stail)
         {
             cout<<shead<<" "<<stail<<endl;
             shead=input[i].head;
             stail=input[i].tail;
         }
         else
             stail=max(stail,input[i].tail);
     }
     cout<<shead<<" "<<stail;
     return 0;
}

 

1089 Intervals