Blog of RuSun

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

P2017 [USACO09DEC]Dizzy Cows G

P2017 [USACO09DEC]Dizzy Cows G

首先对有向边,拓扑排序,得到一个顺序,对于无向边,将顺序调整为拓扑序由小到大即可。

查看代码
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
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 1e5 + 10, M = 1e5 + 10;
queue <int> q;
int n, p1, p2, stmp, din[N], order[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 >> p1 >> p2;
for (int i = 1; i <= n; i++)
hd[i] = -1;
for (int i = 1, a, b; i <= p1; i++)
{
cin >> a >> b;
add(a, b);
din[b]++;
}
for (int i = 1; i <= n ;i++)
if (!din[i])
q.push(i);
while (!q.empty())
{
int t = q.front();
q.pop();
order[t] = ++ stmp;
for (int i = hd[t]; ~i; i = nxt[i])
{
din[edg[i]]--;
if (~din[edg[i]])
q.push(edg[i]);
}
}
for (int i = 1, a, b; i <= p2; i++)
{
cin >> a >> b;
if (order[a] > order[b])
swap(a, b);
cout << a << ' ' << b << endl;
}
return 0;
}