hrbust 1756/哈理工oj Merge Intervals【水题】

Merge Intervals

Time Limit: 1000 MS

Memory Limit: 65535 K

 

Total Submit: 59(25 users)

Total Accepted: 28(24 users)

Rating: 

Special Judge: No

 

Description

Given a collection of intervals, merge all overlapping intervals.

For example,

Given: [1,3],[2,6],[8,10],[15,18];

after meger: [1,6],[8,10],[15,18].

Input

There are multiple test cases.

For each test case:

Line 1: This line contains an integer n indicating the number of intervals.

Line 2..n+1: Each line contains a pair of integers  a and b, indicating the interval [a, b].

1<=n<=100,000

1<=a <= b<=1,000,000,000

Output

Output one line, contains the intervals separated by space after the merge. Output the intervals in lexicographically smaller way.

In other words, if we output [ai,bi] before [aj,bj], there must be ai < aj or ai=aj and bi <= bj.

For more details, referring to the sample.

Sample Input

4

1 3

2 6

8 10

15 18

5

37 65

29 43

30 42

31 87

32 86

Sample Output

[1,6] [8,10] [15,18]

[29,87]

 

思路:贪心模拟即可。。。。

AC代码:

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct zuobiao
{
    int x,y;
} a[100010];
int cmp(zuobiao a,zuobiao b)
{
    if(a.x!=b.x)
        return a.x<b.x;
    else return a.y<b.y;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++)
        {
            scanf("%d%d",&a[i].x,&a[i].y);
        }
        sort(a,a+n,cmp);
        int flag=0;
        int xx,yy;
        for(int i=0; i<n; i++)
        {
            if(flag==0)
            {
                xx=a[i].x;
                yy=a[i].y;
                flag=1;
                continue;
            }
            else
            {
                if(a[i].x<=yy)
                {
                    if(a[i].y>=yy)yy=a[i].y;
                }
                else
                {
                    printf("[%d,%d] ",xx,yy);
                    xx=a[i].x;
                    yy=a[i].y;
                }
            }
            if(i==n-1)
            {
                printf("[%d,%d]\n",xx,yy);
            }
        }
        //printf("%d %d\n",xx,yy);
    }
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值