-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdominos_UVA11504_correct.cpp
108 lines (93 loc) · 1.9 KB
/
dominos_UVA11504_correct.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>
using namespace std;
const int maxn = 20 + 5;
int N, M, in[maxn];
int cntlock, cntscc, pre[maxn], sccno[maxn], low[maxn];
vector<int> G[maxn];
stack<int> S;
void dfs(int u)
{
pre[u] = low[u] = ++cntlock;
S.push(u);
for (int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if (!pre[v])
{
dfs(v);
low[u] = min(low[u], low[v]);
}
else if (!sccno[v])
low[u] = min(low[u], pre[v]);
}
if (low[u] == pre[u])
{
cntscc++;
while (true)
{
int x = S.top();
S.pop();
sccno[x] = cntscc;
if (x == u)
break;
}
}
}
void findSCC()
{
cntlock = cntscc = 0;
memset(pre, 0, sizeof(pre));
memset(sccno, 0, sizeof(sccno));
for (int i = 1; i <= N; i++)
if (!pre[i])
dfs(i);
}
void init()
{
scanf("%d%d", &N, &M);
for (int i = 1; i <= N; i++)
G[i].clear();
int u, v;
while (M--)
{
scanf("%d%d", &u, &v);
G[u].push_back(v);
}
findSCC();
}
int solve()
{
memset(in, 0, sizeof(in));
for (int i = 1; i <= N; i++)
{
int u = sccno[i];
for (int j = 0; j < G[i].size(); j++)
{
int v = sccno[G[i][j]];
if (u != v)
in[v] = 1;
}
}
int ret = 0;
for (int i = 1; i <= cntscc; i++)
if (!in[i])
ret++;
return ret;
}
int main()
{
freopen("dominos_UVA11504_small.in", "r", stdin);
freopen("dominos_UVA11504.out", "w", stdout);
int cas;
scanf("%d", &cas);
while (cas--)
{
init();
printf("%d\n", solve());
}
return 0;
}