问题描述: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.
输入: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.
输出;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.
中文大致题意:有t组测试数据,让你输出n个数,对这n个数有下面m个要求 , 每个要求区间里面的数不想等。要你输出字典序列最小的那个。
比如第三个样例: 5个数,2个区间 : [1,3] [2,4]
首先安排 1-3 的区间,字典序最小且不重复,当然是 1 2 3 了
然后安排 2-4 的区间,2 3 号位已经放了 2 3 了,第四个位置只要不为 2 和 3 即可,那么最放 1,最后没限定,可以放 1
所以答案为 1 2 3 1 1
首先on2复杂度大家都会,然而会超时。这道题思路是去掉重复的区间(取最大的区间,用sort+结构体加几个判断条件来实现),用优先队列维护1-n 中没有出现的数(比如给你一个10 3 [2 8] [1 5] [6 10] 的样例,把1 到 10 push进优先队列后,排序后[1 5] 这个区间先,所以先从优先队列里取 1 2 3 4 5,此时队列剩下6 7 8 9 10,下个区间 [2 8] ,我们先把[ 1 2 )这个区间也就是上次剩下的数丢到优先队列里面去。现在优先队列剩下 1 6 7 8 9 10 ,需要从里面取出8 - 5 个数,所以结果现在是1 2 3 4 5 1 6 7 。下个区间[ 6 10 ] ,丢[2 6)这个区间的数进优先队列,也就是 2 3 4 5 这四个数。再从这四个数取 10 - 8 个,所以答案是
1 2 3 4 5 1 6 7 2 3)
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
using namespace std;
priority_queue <int,vector<int>,greater<int> > q;
struct node{
int a,b;
}nod[100005];
int print[100005];
bool tmp (node a,node b){
if(a.a == b.a){
return a.b > b.b;
}
return a.a < b.a;
}
int main(){
int t;
scanf("%d",&t);
int n,m;
while(t--){
scanf("%d %d",&n,&m);
for(int i = 1;i <= n;i++){
q.push(i);
}
for(int i= 0;i < m;i++){
scanf("%d %d",&nod[i].a,&nod[i].b);
}
sort(nod,nod + m,tmp);
for(int i = 1;i <= n;i++){
print[i] = 1;
}
int l = 0,tmpp,r = 0,r1 = nod[0].a - 1,l1 = nod[0].a;
for(int i = 0;i < m;i++){
if(nod[i].a > l && nod[i].b > r){
r = nod[i].b;
l = nod[i].a;
for(int j = l1;j < l;j++){
q.push(print[j]);
}
for(int j = r1 + 1;j <= nod[i].b;j++){
tmpp = q.top();
q.pop();
print[j] = tmpp;
}
r1 = r;
l1 = l;
}
}
printf("%d",print[1]);
for(int i = 2;i <= n;i++){
printf(" %d",print[i]);
}
puts("");
while(!q.empty()){
q.pop();
}
}
return 0;
}