You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.5 KiB
60 lines
1.5 KiB
2 years ago
|
#include <bits/stdc++.h>
|
||
|
using namespace std;
|
||
|
const int N = 10010, M = N << 1;
|
||
|
|
||
|
// 链式前向星
|
||
|
int e[M], h[N], idx, w[M], ne[M];
|
||
|
void add(int a, int b, int c = 0) {
|
||
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
||
|
}
|
||
|
int num[N]; // 记录每个工人的最终获取多少奖金
|
||
|
int n, m;
|
||
|
int in[N], ans;
|
||
|
|
||
|
int toposort() {
|
||
|
queue<int> q;
|
||
|
int cnt = 0; // 出队列的节点个数
|
||
|
ans = 0;
|
||
|
for (int i = 1; i <= n; i++)
|
||
|
if (in[i] == 0) q.push(i);
|
||
|
|
||
|
while (q.size()) {
|
||
|
int u = q.front();
|
||
|
q.pop();
|
||
|
cnt++;
|
||
|
ans += num[u]; // 出队时,累加出队人员的奖金数量
|
||
|
|
||
|
for (int i = h[u]; ~i; i = ne[i]) {
|
||
|
int j = e[i];
|
||
|
in[j]--;
|
||
|
if (in[j] == 0) {
|
||
|
q.push(j);
|
||
|
num[j] = num[u] + 1; // 需要表示反向图指定的节点比源节点的奖金大1
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
if (cnt != n) ans = -1;
|
||
|
return ans;
|
||
|
}
|
||
|
|
||
|
int main() {
|
||
|
// 加快读入
|
||
|
ios::sync_with_stdio(false), cin.tie(0);
|
||
|
while (cin >> n >> m) {
|
||
|
// 初始化链式前向星
|
||
|
memset(h, -1, sizeof h);
|
||
|
idx = 0;
|
||
|
memset(in, 0, sizeof in);
|
||
|
for (int i = 0; i <= n; i++) num[i] = 888; // 每个人最少888元
|
||
|
|
||
|
while (m--) {
|
||
|
int u, v;
|
||
|
cin >> u >> v;
|
||
|
add(v, u); // 小的向大的建图
|
||
|
in[u]++;
|
||
|
}
|
||
|
printf("%d\n", toposort());
|
||
|
}
|
||
|
return 0;
|
||
|
}
|