Blog of RuSun

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

P2746 [USACO5.3]校园网Network of Schools

P2746 [USACO5.3]校园网Network of Schools

字任务 $A$:显然,答案为缩点后入度为 $0$ 的点。

字任务 $B$ :至少添加多少边,使得所有点在同一强连通分量。不难发现,所有的点在同一强连通分量时,每个点都可以被到达,也都可以到达其他点,所以入度大于 $0$ ,出度大于 $0$ ,而增加一条边,即选择两个点,其中一个增加入度,其中一个增加出度,所以添加的边数即为入度为 $0$ 的点数和出度为 $0$ 的点数的最大值。

查看代码
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
const int N = 1e4 + 10, M = 5e6 + 10;
bool vis[N];
int n, din[N], dout[N];
int idx = -1, hd[N], nxt[M], edg[M];
int cnt, timestamp, id[N], dfn[N], low[N];
stack <int> stk;
void tarjan(int x)
{
dfn[x] = low[x] = ++timestamp;
stk.push(x);
vis[x] = true;
for (int i = hd[x]; ~i; i = nxt[i])
if (!dfn[edg[i]])
{
tarjan(edg[i]);
low[x] = min(low[x], low[edg[i]]);
}
else if (vis[edg[i]])
low[x] = min(low[x], dfn[edg[i]]);
if (dfn[x] == low[x])
{
cnt++;
int y;
do
{
y = stk.top();
stk.pop();
vis[y] = false;
id[y] = cnt;
} while (y != x);
}
}
void add(int x, int y)
{
nxt[++idx] = hd[x];
hd[x] = idx;
edg[idx] = y;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
hd[i] = -1;
for (int i = 1, a; i <= n; i++)
while (cin >> a, a)
add(i, a);
for (int i = 1; i <= n; i++)
if (!dfn[i])
tarjan(i);
for (int i = 1; i <= n; i++)
for (int j = hd[i]; ~j; j = nxt[j])
if (id[i] != id[edg[j]])
{
dout[id[i]]++;
din[id[edg[j]]]++;
}
int x = 0, y = 0;
for (int i = 1; i <= cnt; i++)
{
if (!din[i])
x++;
if (!dout[i])
y++;
}
cout << x << endl;
if (cnt == 1)
cout << 0;
else
cout << max(x, y);
return 0;
}