Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2999 [USACO10NOV]Chocolate Milk S

P2999 [USACO10NOV]Chocolate Milk S

按照题意拓扑排序即可。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 1e5 + 10, M = 1e5 + 10;
bool vis[N];
int n, cnt, din[N], dout[N], flow[N];
int idx = -1, hd[N], nxt[M], edg[M];
void add (int a, int b)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
}
int main ()
{
cin >> n;
for (int i = 1; i <= n; i++)
hd[i] = -1;
for (int i = 1, a, b; i < n; i++)
{
cin >> a >> b;
add(a, b);
din[b]++;
dout[a]++;
}
queue <int> q;
for (int i = 1; i <= n; i++)
if (!din[i])
{
cnt++;
flow[i] = 1;
vis[i] = true;
q.push(i);
}
while (!q.empty())
{
int t = q.front();
q.pop();
if (dout[t] > 1)
continue;
for (int i = hd[t]; ~i; i = nxt[i])
{
flow[edg[i]] += flow[t];
din[edg[i]]--;
if (!din[edg[i]])
q.push(edg[i]);
}
}
for (int i = 1; i <= n; i++)
if (flow[i] == cnt && !vis[i])
cout << i << endl;
return 0;
}