Distinct Values
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3336 Accepted Submission(s): 523
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 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.
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
题意:给定m个区间要求每个区间内的数互不相同,求字典序最小的序列。
思路:先将数组全部赋值成1,然后依次处理每个区间,没有处理到的区间就不用管。处理区间的方法如下:
1.将所有区间按照左端点从小到大排序。
2.用set(去重、排序)存储当前可用的所有数。
3.用left和right保存上个区间的左右端点的值,这样我们就可以将left到当前区间的左端点的所有值重新放在set里面,以便下次使用。
4.给当前区间依次赋值,从set中取,取一个删一个。
AC代码:
#include<cstdio>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 100005;
struct st
{
int l,r;
}a[N];
set<int> s;
bool cmp(st a,st b)
{
if(a.l==b.l)
return a.r>b.r;
else return a.l<b.l;
}
int main()
{
int t,n,m,ans[N];
scanf("%d",&t);
while(t--)
{
s.clear();
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&a[i].l,&a[i].r);
}
sort(a+1,a+m+1,cmp);
for(int i=1;i<=n;i++)
s.insert(i);
for(int i=1;i<=n;i++)
ans[i] = 1;
int left=1,right=0;
set<int>::iterator itsetIntTest;
for(int i=1;i<=m;i++)
{
int l=a[i].l;
int r= a[i].r;
if(r<=right)
continue;
for(int i=left;i<l;i++)//上个区间的左端点到当前区间的左端点都可以使用了,其中可能有重复的数字,set去重。
s.insert(ans[i]);
itsetIntTest = s.begin();
if(l<=right)//当前区间的左端点小于上一个区间的右端点
{
for(int i=right+1;i<=r;i++)
{
ans[i] = *itsetIntTest++;
s.erase(ans[i]);
}
}
else
{
for(int i=l;i<=r;i++)
{
ans[i] = *itsetIntTest++;
s.erase(ans[i]);
}
}
left=l;
right=r;
}
for(int i=1;i<=n-1;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
}
return 0;
}