ABC 223 | D - Restricted Permutation
题目描述
序列为的一个排列,对于排列,有个限制条件,表示要在左侧,问是否存在这样的排列,若存在,则输出字典序最小的排列;若不存在,则输出-1
。
数据范围
解题思路
对于在之前这样的条件可以用有向边表示,据此建图,容易发现答案即为拓扑序,但此处要求输出字典序最小的排列,因此需要将拓扑排序中的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;
}
分类:
拓扑排序
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库