HDU 5638 拓扑排序+优先队列

时间:2023-03-08 16:57:19

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5638

题意:

给你一个DAG图,删除k条边,使得能个得到字典序尽可能小的拓扑排序

题解:

把拓扑排序的算法稍微改一下,如果某个顶点的入度小于k也把它加到优先队列里面去。

k减小后队列里面会有些点不满足<=k,直接踢出来就好了。

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<functional>
using namespace std; typedef long long LL;
const int maxn = ;
const int maxm = maxn << ;
const int mod = 1e9 + ;
int n, m, k; vector<int> G[maxn];
int ind[maxn], used[maxn],inq[maxn]; void init() {
for (int i = ; i <= n; i++) G[i].clear();
memset(ind, , sizeof(ind));
memset(inq, , sizeof(inq));
memset(used, , sizeof(used));
} int main() {
int tc;
scanf("%d", &tc);
while (tc--) {
scanf("%d%d%d", &n, &m, &k);
init();
for (int i = ; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
ind[v]++;
}
priority_queue<int,vector<int>,greater<int> > pq;
for (int i = ; i <= n; i++) {
if (ind[i] <= k) pq.push(i),inq[i] = ;
}
vector<int> ans;
while (!pq.empty()) {
while (ind[pq.top()]>k) {
inq[pq.top()] = ;
pq.pop();
}
int x = pq.top(); pq.pop();
inq[x] = ;
k -= ind[x];
ans.push_back(x); used[x] = ;
for (int i = ; i < G[x].size(); i++) {
int v = G[x][i];
ind[v]--;
if (ind[v] <= k&&!inq[v]&&!used[v]) {
pq.push(v);
inq[v] = ;
}
}
}
LL cnt = ;
for (int i = ; i < ans.size(); i++) {
cnt += (LL)(i + )*ans[i];
cnt %= mod;
}
printf("%lld\n", cnt);
}
return ;
}