POJ1089-Intervals

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,然后给出N个整数区间,如果两个区间有交集,则合并,最后输出合并后的区间。注意,合并后的区间可能不止一个!

怎么说呢?英语太差了!百度翻译来着,但是真的不知到他到底翻译了个什么玩意儿!然后上网查,那些大佬肯定都是英语学霸,都说了“水题”二字,其他的啥也没说!虽然题是很水,但是题意都不知道再水也不水了!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#define N 50005

using namespace std;

struct node{
	int l,r;
};

node book[N];

bool cmp(node a,node b)
{
	if(a.l==b.l)
		return a.r<b.r;
	return a.l<b.l;
}

int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d",&book[i].l,&book[i].r);
	}
	sort(book+1,book+n+1,cmp);
	int l=book[1].l,r=book[1].r;
	for(int i=2;i<=n;i++)
	{
		if(book[i].l>r)
		{
			printf("%d %d\n",l,r);
			l=book[i].l;
			r=book[i].r;
		}
		else
		{
			if(book[i].r>r)
				r=book[i].r;
		}
	}
	printf("%d %d\n",l,r);
	return 0;
 } 
发布了46 篇原创文章 · 获赞 16 · 访问量 396

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105148449