Distinct Values
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3304 Accepted Submission(s): 1073
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≠ajholds.
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.
Sample Input
3
2 1
1 2
4 2
1 2
3 4
5 2
1 3
2 4
Sample Output
1 2
1 2 1 2
1 2 3 1 1
题意:输入T组案例,每组案例中要组成n个数字典序最小,它有m个要求,每个要求给l和r两个数,表示在[l,r]区间内的数不同。所填的数从1开始。
题解:这个地方也是用贪心算法。先用pre数组预处理保存以这个终点开始能到的最左边的序列位置。pre[r] = min(pre[r], l);(这个地方删除掉了大区间包含的小区间)
例如第三组样例
5 2
1 3
2 4
--------------
1 2 3
2 3 4
pre数组
1 1 1 2 5
--------------
也就是说pre[i]储存的是 [pre[i],i]之间的数要不同。
之后用set进行维护(这里学到了,set内部已经是从小到大排好序了)
用一个pl表示上一次处理到的位置。ret数组是答案。set<int>val 表示可用数的集合。
[pl,pre[i]-1]这个区间内的数能重复用,将前面的答案重新放入val集合。ret[i] = *val.begin(); 【其中*val.begin() 是集合中最小的数】
已经用了的数字就从集合中删除。val.erase(ret[i]);
代码:
#include <cstdio>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100100;
int t, n, m, pre[N], l, r, ret[N];
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
pre[i] = i;
}
for (int i = 0; i < m; i++) {
scanf("%d %d", &l, &r);
pre[r] = min(pre[r], l);
}
for (int i = n-1; i >= 1; i--) {
pre[i] = min(pre[i], pre[i+1]);
}
int pl = 1;
set<int> val; // 表示当前可用数的集合
for (int i = 1; i <= n; i++) {
val.insert(i);
}
for (int i = 1; i <= n; i++) {
while (pl < pre[i]) {
val.insert(ret[pl]);
pl++;
}
ret[i] = *val.begin();
val.erase(ret[i]);
}
for (int i = 1; i <= n; i++) {
if (i != 1) printf(" ");
printf("%d", ret[i]);
}
puts("");
}
}