当前位置: 代码迷 >> 综合 >> 【hdu2647】【拓扑排序】
  详细解决方案

【hdu2647】【拓扑排序】

热度:31   发布时间:2024-01-04 11:37:37.0

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

【题意】

给你m个限制关系a b,表明a比b的工资高,最低888,问最小需要发多少工资

【思路】

拓扑排序

【代码】

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+5;
using ll = long long;
vector<int>v[maxn];
int du[maxn];
int vis[maxn];int main() {int n, m;while (~scanf("%d%d", &n, &m)) {for (int i = 1; i <= n; i++) {v[i].clear();}memset(du, 0, sizeof(du));memset(vis, 0, sizeof(vis));while (m--) {int x, y;scanf("%d%d", &x, &y);v[y].push_back(x);du[x]++;}queue<pair<int,int> >q;ll ans = 0;int base = 888;for (int i = 1; i <= n; i++) {if (du[i] == 0) {q.push({ i ,base });vis[i] = 1;ans += base;}}while (q.size()) {auto p = q.front(); q.pop();int x = p.first;int w = p.second;for (int y : v[x]) {if (vis[y])continue;du[y]--;if (du[y] == 0) {ans += w + 1;q.push({ y,w + 1 });vis[y] = 1;}}}int flag = 1;for (int i = 1; i <= n; i++) {if (!vis[i]) {printf("-1\n");flag = 0;break;}}if (flag) {printf("%d\n", ans);}}
}