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 a_l..
r(l≤i<j≤r),ai≠aj
r
(
l
≤
i
<
j
≤
r
)
,
a
i
≠
a
j
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)
(
1
≤
n
,
m
≤
10
5
)
– the length of the array and the number of facts. Each of the next m lines contains two integers
li
l
i
and
ri
r
i
(
1≤li≤ri≤n
1
≤
l
i
≤
r
i
≤
n
).
It is guaranteed that neither the sum of all n nor the sum of all m exceeds
106
10
6
.
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
这题不难,能很容易想到构造思路,关键是实现效率问题。也算是签到题吧。
按照左端点排序,然后依次考虑,维护L,因为区间的左端点是递增的,所以L会一直往右滑,把可用的点重新去掉标记。
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define maxx 100005
using namespace std;
int ans[maxx];
int a[maxx];//这个其实可以用map来代替,效率会更快一点
struct node
{
int l,r;
}p[maxx];
int cmp(node x1,node x2)
{
return x1.l<x2.l;
}
int main()
{
int t;
cin>>t;
int n,q;
while(t--)
{
memset(a,0,sizeof(a));
memset(ans,0,sizeof(ans));
scanf("%d%d",&n,&q);
for(int i=0;i<q;i++)
scanf("%d%d",&p[i].l,&p[i].r);
sort(p,p+q,cmp);
int cnt=1;
for(int i=p[0].l;i<=p[0].r;i++)
{
ans[i]=cnt;
a[cnt++]=1;
}
int L=p[0].l;
int R=p[0].r;
//cout<<"jaja"<<endl;
for(int i=1;i<q;i++)
{
for(;L<p[i].l;L++)
a[ans[L]]=0;
if(R<p[i].l)
{
cnt=1;
for(int j=p[i].l;j<=p[i].r;j++)
{
while(a[cnt])cnt++;
ans[j]=cnt;
a[cnt++]=1;
}
R=p[i].r;
}
else
{
if(R<p[i].r)
{
cnt=1;
for(int j=R+1;j<=p[i].r;j++)
{
while(a[cnt])cnt++;
ans[j]=cnt;
a[cnt++]=1;
//cout<<"cnt: "<<cnt<<endl;
}
R=p[i].r;
}
}
}
for(int i=1;i<n;i++)
printf("%d ",(ans[i]?ans[i]:1));
printf("%d\n",(ans[n]?ans[n]:1));
}
return 0;
}