Distinct Values HDU - 6301
先感謝下在B站直播講題的清華大佬。ˋ( ° ▽、° )
題目:
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
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≤10e5) – 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 10e6.
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 下標的範圍內不能有重複數字。
思路:
算法是貪心。
每次輸入l 和 r 時,把r 下標的數組數據改爲 l。m組限制輸入完畢後,從設置的下標數組從後往前比較,倒數第二個和倒數第一個比較,一直遍歷到第一個。這樣就能把每個最後要限制的不同的範圍的數據改爲l 的下標。然後利用set默認從小到大排序的便利,先初始化set(從1到n),每個範圍內開始遍歷每次有可以用的數據就從set中提出並erase去除。
AC代碼:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <set>
using namespace std;
const int SIZE = 1e5+5;
int pre[SIZE];
int arr[SIZE];
set<int> s;
int main() {
int t;
scanf("%d", &t);
while(t--) {
int m, n, l, r;
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(l, pre[r]);
}
for(int i = n-1; i >= 1; i--) {
pre[i] = min(pre[i], pre[i+1]);
}
s.clear();
for(int i = 1; i <= n; i++) {
s.insert(i);
}
int js = 1;
for(int i = 1; i <= n; i++) {
while(js < pre[i]) {
s.insert(arr[js]);
js++;
}
arr[i] = *s.begin();
s.erase(arr[i]);
}
for(int i = 1; i <= n; i++) {
printf("%d", arr[i]);
printf("%c", i == n ? '\n' : ' ');
}
}
return 0;
}