ABC 223 | D - Restricted Permutation
题目描述
序列\(P\)为\((1, 2, 3, ...,N)\)的一个排列,对于排列\(P\),有\(M\)个限制条件\((A_i, B_i)\),表示\(A_i\)要在\(B_i\)左侧,问是否存在这样的排列\(P\),若存在,则输出字典序最小的排列;若不存在,则输出-1。
数据范围
- \(2 \le N \le 2 \times 10^5\)
- \(2 \le M \le 2 \times 10^5\)
- \(1 \le A_i, B_i \le N\)
- \(A_i \neq B_i\)
解题思路
对于\(A_i\)在\(B_i\)之前这样的条件可以用有向边表示,据此建图,容易发现答案即为拓扑序,但此处要求输出字典序最小的排列,因此需要将拓扑排序中的queue改为priority_queue。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <unordered_set>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10, M = N;
int h[N], e[M], ne[M], idx;
int n, m;
int du[N], ans[N], x;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
bool topsort()
{
priority_queue<int, vector<int>, greater<int>> q;
for(int i = 1; i <= n; i ++)
if(du[i] == 0) q.push(i);
while(q.size()){
auto t = q.top(); q.pop();
ans[x ++] = t;
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
du[j] --;
if(!du[j]){
q.push(j);
}
}
}
if(x < n) return false;
return true;
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
unordered_set<ll> S;
while(m --){
int a, b;
scanf("%d%d", &a, &b);
ll hash = a * 1000000ll + b;
if(!S.count(hash)){
add(a, b);
du[b] ++;
S.insert(hash);
}
}
if(!topsort()) puts("-1");
else{
for(int i = 0; i < x; i ++) printf("%d ", ans[i]);
}
return 0;
}

浙公网安备 33010602011771号