-
Notifications
You must be signed in to change notification settings - Fork 1
/
1034 - Hit the Light Switches.cpp
84 lines (83 loc) · 1.72 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
#include<bits/stdc++.h>
using namespace std;
#define mx 10005
typedef vector<int> vi;
vi adj[mx];
int vis [mx];
int out[mx];
int in[mx];
struct Node
{
int x;
int outd;
int ind;
Node(int a, int b,int c){
x = a;
outd = b;
ind = c;
}
};
bool compout(Node a, Node b)
{
return a.outd > b.outd;
}
bool compin(Node a, Node b)
{
return a.ind < b.ind;
}
void dfs(int s)
{
vis[s] = 1;
for(int i=0; i<adj[s].size(); i++){
if(vis[adj[s][i] ]==-1){
dfs(adj[s][i]);
}
}
}
int main()
{
int tc,n,m,a,b,ans;
scanf("%d",&tc);
for(int t=1; t<=tc ;t++){
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++){
vis[i] = -1;
out[i] = 0;
in[i] = 0;
}
for(int i=1; i<=m; i++){
scanf("%d%d",&a, &b);
adj[a].push_back(b);
out[a]++;
in[b]++;
}
vector<Node > v;
for(int i=1; i<=n; i++){
v.push_back(Node(i, out[i], in[i]));
}
sort(v.begin(), v.end(),compout);
ans = 0;
for(int i=0; i<n; i++){
int s =v[i].x;
if(vis[s]==-1){
dfs(s);
ans++;
}
}
for(int i=1; i<=n; i++){
vis[i] = -1;
}
int tem=0;
sort(v.begin(), v.end(),compin);
for(int i=0; i<n; i++){
int s =v[i].x;
if(vis[s]==-1){
dfs(s);
tem++;
}
}
ans = min(ans, tem);
printf("Case %d: %d\n",t,ans);
for(int i=1; i<=n; i++) adj[i].clear();
}
}