HDU 6301 Distinct Values【优先队列】(2018 MUTC 1)

Distinct Values

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2631    Accepted Submission(s): 845


 

Problem Description

Chiaki has an array of n positive integers. You are told some facts about the array: for every two elements ai and aj in the subarray al..r (l≤i<j≤r), ai≠aj holds.
Chiaki would like to find a lexicographically minimal array which meets the facts.

 

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains two integers n and m (1≤n,m≤105) -- the length of the array and the number of facts. Each of the next m lines contains two integers li and ri (1≤li≤ri≤n).

It is guaranteed that neither the sum of all n nor the sum of all m exceeds 106.

 

Output

For each test case, output n integers denoting the lexicographically minimal array. Integers should be separated by a single space, and no extra spaces are allowed at the end of lines.

Input

3

2 1

1 2

4 2

1 2

3 4

5 2

1 3

2 4

Output

1 2

1 2 1 2

1 2 3 1 1

题目大意:

要求输出n个数字的数组,但是给出了m个限制区间,每一个区间里不能有相同的数字,并且输出的n个数字的数组的字典序要求最小。

解法:

把输入的m个限制区间用sort贪心排序,left小的排在最左边,left相等的情况,right大的排在左边。然后for循环m次,如果区间left相等就continue掉,不用管他,因为我把覆盖区间最大的放在最左边,left相等的只是它的一个子区间。我们先初始化两个变量left=right=-1;我们只用取两种情况,一种是当前区间的left>right,另一种是当前区间的left<=right&&当前区间的right>right。如图所示:

第一种情况:

第二种情况:

对于第一种情况,限制区间没有交集,所以我们可以直接从1开始赋值。

第二种情况,我们需要把前一个区间没有交集的地方用过的数字标记掉,以免重复使用。

(可以直接用优先队列写,不会的童鞋,可以学我用数组模拟优先队列~)

附上AC代码:

#include <bits/stdc++.h>
#include <queue>
using namespace std;
struct KNIGHT{
	int l,r;
}p[1000000];
int cmp(KNIGHT a,KNIGHT b){
	if(a.l == b.l) return a.r > b.r;
	return a.l < b.l;
}
int a[1000000],mark[1000000];
int main(){
	int t,n,m,count;
	scanf("%d", &t);
	while(t--){
		scanf("%d%d", &n, &m);
		for(int i = 0;i < m; i++)
			scanf("%d%d", &p[i].l, &p[i].r);
		sort(p , p + m , cmp);
		int left = -1, right = -1;
		for(int i = 0;i < m; i++){
			if(p[i].l > right){
				count = 1;
				for(int j = p[i].l;j <= p[i].r; j++)
					a[j] = count++;
				left = p[i].l; right = p[i].r;
			}else if(p[i].l <= right && p[i].r > right){
				count = 1;
				for(int j = right;j >= p[i].l; j--)
					mark[a[j]] = 1;
				for(int j = p[i].l;j <= p[i].r; j++){
					if(a[j]) continue;
					if(!mark[count])
						a[j] = count++;
					else{
						count++; j--;
					}
				}
				for(int j = 1;j <= n; j++)
					mark[j] = 0;
				left = p[i].l;right = p[i].r;
			}
		}
		if(a[1]) printf("%d", a[1]);
		else printf("1");
		for(int i = 2;i <= n; i++)
			if(a[i]) printf( " %d", a[i]);
			else printf(" 1");
		printf("\n");
		if(t != 0)
			for(int i = 1;i <= n; i++) a[i] = 0;
	}
}
发布了22 篇原创文章 · 获赞 19 · 访问量 3553

猜你喜欢

转载自blog.csdn.net/KnightHONG/article/details/81184834