P
r
o
b
l
e
m
D
e
s
c
r
i
p
t
i
o
n
\color{blue}Problem Description
ProblemDescription
Dandelion’s uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards.
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a’s reward should more than b’s.Dandelion’s unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work’s reward will be at least
888
888
888 , because it’s a lucky number.
I
n
p
u
t
\color{blue}Input
Input
One line with two integers
n
n
n and
m
m
m ,stands for the number of works and the number of demands .
(
n
<
=
10000
,
m
<
=
20000
)
(n<=10000,m<=20000)
(n<=10000,m<=20000)
then
m
m
m lines ,each line contains two integers
a
a
a and
b
b
b ,stands for a’s reward should be more than b’s.
O
u
t
p
u
t
\color{blue}Output
Output
For every case ,print the least money dandelion ‘s uncle needs to distribute .If it’s impossible to fulfill all the works’ demands ,print
−
1
-1
−1.
S a m p l e I n p u t \color{blue}Sample Input SampleInput
2 1
1 2
2 2
1 2
2 1
S a m p l e O u t p u t \color{blue}Sample Output SampleOutput
1777
-1
输入 a a a和 b b b,表示 a a a的钱比 b b b多,如果我们正向建图,那么就是 a − > b a->b a−>b的一条边,这时候去拓扑排序的话应该是 a a a先入队,那么就不好判断 a a a的金额。
如果反向建图,那么就是 b − > a b->a b−>a的一条边,那么拓扑排序时就是 b b b先入队,那么 a a a的金额就是 b b b的金额+1就行了。
输出-1的情况就是有环,拓扑排序的时候记录一下正常分配的有多少个,然后和 n n n比较一下就行了。
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e4 + 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-7;
#define endl '\n'
#define pb(a) push_back(a)
#define ALL(x) x.begin(), x.end()
#define SIZE(x) int(x.size())
#define IOS ios::sync_with_stdio(0);
int r[N], in[N];
vector<int> e[N];
bool vis[N];
int main() {
int n, m;
while (~scanf("%d%d", &n, &m)) {
memset(r, 0, sizeof(r));
memset(vis, 0, sizeof(vis));
memset(in, 0, sizeof(in));
for (int i = 1; i <= n; ++i) e[i].clear();
for (int i = 1; i <= m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
in[u] = ++r[u]; //代表入度和增加的金钱
e[v].pb(u);
}
queue<int> q;
for (int i = 1; i <= n; ++i) {
if (!r[i]) q.push(i);
}
int ans = 0, cnt = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
cnt++;
vis[u] = 1;
ans += 888 + in[u];
for (int i = 0; i < SIZE(e[u]); ++i) {
int v = e[u][i];
if (!vis[v] && --r[v] == 0) {
in[v] = 1 + in[u]; //在当前加的金钱的基础上再加1
q.push(v);
}
}
}
if (cnt != n) { //有环
printf("-1\n");
} else {
printf("%d\n", ans);
}
}
return 0;
}