Strict Permutation Codechef Problem Solution | STRPERM
You are given an integer
(Xi,Yi) , denoting that the elementXi(1≤Xi≤N) must appear in the prefix of lengthYi . Formally, if the index of the elementXi isKi (i.e,PKi=Xi ), then the condition1≤Ki≤Yi must hold.
Print -1
if no such permutation exists. In case multiple permutations that satisfy all the conditions exist, find the lexicographically smallest one.
Note: If two arrays
.
Input Format
- The first line of input will contain a single integer
T , denoting the number of test cases. - The first line of each test case contains two space-separated integers
N andM – the length of permutation and the number of conditions to be satisfied respectively. - The next
M lines describe the conditions. Thei -th of theseM lines contains two space-separated integersXi andYi
Output Format
For each test case, output a single line containing the answer:
- If no permutation satisfies the given conditions, print
−1
. - Otherwise, print
N space-separated integers, denoting the elements of the permutation. If there are multiple answers, output the lexicographically smallest one.
Constraints
1 ≤ T ≤ 10^5 1 ≤ N ≤ 10^5 1 ≤ M ≤ N 1 ≤ Xi, Yi ≤ N Xi ≠ Xj for each1 ≤ i < j ≤ M The sum of N over all test cases won’t exceed2⋅10^5
Sample Input 1
4
3 2
2 1
1 2
4 3
1 2
4 1
3 2
4 1
2 3
5 2
5 4
3 2
Sample Output 1
2 1 3
-1
1 2 3 4
1 3 2 5 4
Explanation
Test case
Test case
Test case
using namespace std;
int main() {
int T;
cin >> T;
while(T--){
int n,m;
cin >> n >> m;
vectorv[n+1];
unordered_mapff;
for(int i=0;i> x >> y;
v[y].push_back(x);
ff[x]++;
}
for(int i=1;i<=n;i++){
if(ff[i])continue;
v[n].push_back(i);
}
vectorans;
priority_queuepq;
for(int i=n;i>=1;i--){
for(auto j:v[i])pq.push(j);
if(pq.empty()){
cout << -1 << endl;
break;
}
ans.push_back(pq.top());
pq.pop();
}
if(ans.size()
0 Comments