LightOj 1034 (Hit the Light Switches)

#lightoj #cp #problem_solving #topsort #scc #graph_theory

Idea


Topological Sort / Strongly Connected Component

  • To visit all node we can simply touch minimum number of node by using topological sort.
    OR just find the number of SCC
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

/**Which of the favors of your Lord will you deny ?**/

#include<bits/stdc++.h>
using namespace std;

#define LL long long
#define PII pair<int,int>
#define MP make_pair
#define F first
#define S second

vector<int>adj[100010];
bool visited[10010];
stack<int>stk;

void dfs1(int node)
{
visited[node]=true;

for(int next:adj[node])
{
if(visited[next]==false)
dfs1(next);
}

stk.push(node);
}

void dfs2(int node)
{
visited[node]=true;

for(int next:adj[node])
{
if(visited[next]==false)
dfs2(next);
}

//stk.push(node);
}

void init()
{
for(int i=0;i<100010;i++)
adj[i].clear();

fill(visited,visited+10010,false);

while(!stk.empty())
stk.pop();

}

int main()
{
//freopen("LightOj1034.txt","w",stdout);

int tc;
scanf("%d",&tc);

for(int i=1;i<=tc;i++)
{
init();

int nodes,edges;
scanf("%d %d",&nodes,&edges);

for(int j=1;j<=edges;j++)
{
int a,b;
scanf("%d %d",&a,&b);

adj[a].push_back(b);
}

fill(visited,visited+10010,false);

for(int j=1;j<=nodes;j++)
if(visited[j]==false)
dfs1(j);

fill(visited,visited+10010,false);

int con_comp=0;
int siz=stk.size();

for(int j=0;j<siz;j++)
{
int now=stk.top();
stk.pop();

if(visited[now]==false)
{
con_comp++;
dfs2(now);
}
}

printf("Case %d: %d\n",i,con_comp);

}

return 0;
}