forked from hackerkid/LightOJ-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1034-Hit-the-Light-Switches.cpp
136 lines (98 loc) · 1.7 KB
/
1034-Hit-the-Light-Switches.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <stack>
using namespace std;
bool visited[10004];
int n;
vector < vector <int > > graph;
vector < vector <int > > transpose;
stack <int> track;
int dfs(int j)
{
visited[j] = true;
int t;
for (int i = 0; i < graph[j].size(); i++) {
t = graph[j][i];
if(visited[t] == false) {
dfs(t);
}
}
track.push(j);
}
int dfsbro(int j)
{
visited[j] = true;
int t;
for (int i = 0; i < transpose[j].size(); i++) {
t = transpose[j][i];
if(visited[t] == false) {
dfsbro(t);
}
}
}
int dfsbro2(int j)
{
visited[j] = true;
int t;
for (int i = 0; i < graph[j].size(); i++) {
t = graph[j][i];
if(visited[t] == false) {
dfsbro2(t);
}
}
}
int trans()
{
vector < vector <int > > temp(n+5);
swap(temp, transpose);
int t;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < graph[i].size(); j++) {
t = graph[i][j];
transpose[t].push_back(i);
}
}
}
int main()
{
int x;
int y;
int m;
int count;
int tt;
int t;
scanf("%d", &t);
for (int cases = 1; cases <= t; cases++) {
scanf("%d", &n);
scanf("%d", &m);
vector < vector <int > > temp(n+5);
memset(visited, 0, sizeof(visited));
stack <int> track2;
swap(track, track2);
swap(temp, graph);
for (int i = 0; i < m; i++) {
scanf("%d", &x);
scanf("%d", &y);
graph[x].push_back(y);
}
for (int i = 1; i <= n; i++) {
if(visited[i] == false) {
dfs(i);
}
}
// trans();
memset(visited, 0, sizeof(visited));
count = 0;
while(!track.empty()) {
tt = track.top();
track.pop();
if(visited[tt] == false) {
dfsbro2(tt);
count++;
}
}
printf("Case %d: %d\n", cases, count);
}
}