(一)题面:
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≤1e5) -- 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
(二)题意:
给定一个n以及k各区间,需要构造一个字典序最小的序列,使得给定的各自区间内的的数均不相等。
(三)题解:
①如果某个位置没有被区间覆盖过,那么这个位置填1。
②如果一个区间完全A包含在另外一个B内,那么区间A不需要被考虑。
③如果两个区间部分重叠(区间A在前,B在后--按左端点排序),那么重叠部分的数字不需要被考虑,而A中未重叠部分的数字可以被重新填入B的为重叠部分。
④因为要保证字典序尽可能小,所以每次在设置某个位置的值的时候,我们都尽可能地选取小的数。
⑤用优先队列或者set维护一下当前可以填放的最小的数即可。
⑥复杂度O(nlogn)。
(四)代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#include<functional>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
struct node{
int l,r;
bool operator < (node n1){
return l<n1.l||(l==n1.l&&r>n1.r);
}
}s[maxn];
int ans[maxn];
int main(){
freopen("in.txt","r",stdin);
int T,n,m;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)scanf("%d%d",&s[i].l,&s[i].r);
sort(s,s+m);
priority_queue<int,vector<int>,greater<int> >Q;
for(int i=1;i<=n;i++)Q.push(i);
int l=s[0].l,r=s[0].r;
for(int i=l;i<=r;i++)ans[i]=Q.top(),Q.pop();
for(int i=1;i<m;i++){
if(r<s[i].l){
for(int p=l;p<=r;p++)Q.push(ans[p]);
l=s[i].l,r=s[i].r;
for(int p=l;p<=r;p++)ans[p]=Q.top(),Q.pop();
}
else if(s[i].r>r){
for(int p=l;p<s[i].l;p++)Q.push(ans[p]);
for(int p=r+1;p<=s[i].r;p++)ans[p]=Q.top(),Q.pop();
l=s[i].l,r=s[i].r;
}
}
printf("1");
for(int i=2;i<=n;i++)
printf(" %d",ans[i]?ans[i]:1);
printf("\n");
memset(ans,0,sizeof ans);
}
return 0;
}
(五)总结:
话说赛场上队友想到解法了哇,但是认为这是一种暴力解法,并且复杂度计算错误,所以没有及时地去写,赛后经提醒才发现这么写的复杂度为O(nlogn)。
实际上,对于每一个位置来说,队列最多Push一次以及Pop()一次,故复杂度为O(nlogn)。