英文
Time Limit:1s Memory Limit:256M
Description
Input n interval,output the union set from small to large.
Input
The first line contains an integer n. 1<=k<=100
The next n lines,each line contains two integer a,b 1<=a,b<=10^8
Output
The union set.
x lines,each line output an interval.
Sample Input
3
2 5
1 4
7 8
Sample Output
1 5
7 8
中文
时间:1s 空间:256M
题目描述:
从键盘上任意输入n个区间,然后按从小到大的顺序依次输出n个区间的并集。
输入格式:
第一行,区间个数n
以下n行,每行两个数a、b
输出格式:
n个区间的并集,x行,每行一个区间,坐标轴的左边的区间先输出。
样例输入:
3
2 5
1 4
7 8
样例输出:
1 5
7 8
约定:
1<=n<=100,1<=a,b<=10^8
提示:
我们可以发现,a与b很大,用桶很难实现。但我们可以发现n特别小,只用暴力就行了。代码如下:
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 101
using namespace std ;
struct mrz
{
int x , y ;
} p [ N ] ;//输入的集合
bool cmp ( mrz k1 , mrz k2 )
{
return k1 . x < k2 . x ;
}
int n , t = 0 ;
mrz ans [ 100 ] ;//记录答案,以合并的集合
int main ( )
{
scanf ( "%d" , & n ) ;
for ( int i = 1 ; i <= n ; i ++ )
{
scanf ( "%d %d" , & p [ i ] . x , & p [ i ] . y ) ;
if ( p [ i ] . x > p [ i ] . y ) swap ( p [ i ] . x , p [ i ] . y ) ;
}//保证左端点小于右端点
sort ( p + 1 , p + n + 1 , cmp ) ;
bool bo ;
for ( int i = 1 ; i <= n ; i ++ )
{
int j ;
bo = 0 ;//记录该集合是否可以与已有集合合并
for ( j = 1 ; j <= t ; j ++ ) //每个集合逐一合并
{
if ( p [ i ] . x < ans [ j ] . x && p [ i ] . y > ans [ j ] . x )
{
ans [ j ] . x = p [ i ] . x ;
ans [ j ] . y = max ( p [ i ] . y , ans [ j ] . y ) ;
bo = 1 ;
break ;
}
if ( p [ i ] . x > ans [ j ] .x && p [ i ] . x < ans [ j ] . y )
{
ans [ j ] . y =max ( p [ i ] . y , ans [ j ] . y ) ;
bo = 1 ;
break ;
}
}
if ( bo == 0 )//无法合并,就在答案中新开一个集合
{
t ++ ;
ans [ t ] . x = p [ i ] . x ;
ans [ t ] . y = p [ i ] . y ;
}
sort ( ans + 1 , ans + t + 1 , cmp ) ;//100以内的数排序就是秒杀,就是这么暴力
j = t ;
while ( j >= 2 )//让ans内部的集合不能在合并
{
if ( ans [ j ] . x < ans [ j - 1 ] . y )
{
t -- ;
ans [ j - 1 ] . y = max ( ans [ j - 1 ] . y , ans [ j ] . y ) ;
}
j -- ;
}
}
for ( int i = 1 ; i <= t ; i ++ ) printf ( "%d %d\n" , ans [ i ] . x , ans [ i ] . y ) ;
return 0 ;
}
相关链接:
XJOI 题解小全:
https://blog.csdn.net/zj_mrz/article/details/80949787
XJOI 3410 看图找规律 题解:
https://blog.csdn.net/zj_mrz/article/details/81044076
XJOI 3287 离散化 题解:
https://blog.csdn.net/zj_mrz/article/details/81037239