MYF

HDU 2767 Proving Equivalences

题目链接

HDU 2767

解题方法:强连通分量

题目分析

题目大意

给出一个n个点,m条边的有向图,问在图中最少要加多少条边能使得该图变成一个强连通图

解析

为了使图成为强连通图,那么我们就要消灭所有入度和出度为0的点。

遍历每一条边,不妨设其是u指向v,那么u所在的强连通分量就有出度,v所在的强连通分量就有入度,我们统计出有多少个强连通分量的有出度,多少个强连通分量有入度,然后取两者的较大者即可,当图是一个强连通分量图时,也就是说图中没有需要加边的点,那么我们就输出0,否则,我们取max(入度为0的点的个数,出度为0的点的个数)即可。

代码

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
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <iomanip>
#include <bitset>
#include <cstring>
#include <iostream>
#include <iosfwd>
#include <deque>
#include <algorithm>
#define Memset(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)
#define PB push_back
#define MP make_pair
#define rt(n) (i == n ? '\n' : ' ')
#define hi printf("Hi----------\n")
#define IN freopen("input.txt","r",stdin);
#define OUT freopen("output.txt","w",stdout);
#define debug(x) cout<<"Debug : ---"<<x<<"---"<<endl;
#define debug2(x,y) cout<<"Debug : ---"<<x<<" , "<<y<<"---"<<endl;
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int mod=1000000007;
const int INF=0x3f3f3f3f;
const double eps=1e-11;
const int maxn=20000+10;
int dfs_clock;//时钟
int scc_cnt;//强连通分量总数
vector<int> G[maxn];//G[i]表示i节点指向的所有点
int pre[maxn]; //时间戳
int low[maxn]; //u以及u的子孙能到达的祖先pre值
int sccno[maxn];//sccno[i]==j表示i节点属于j连通分量
bool out[maxn],in[maxn];
stack<int> S;
void dfs(int u){
pre[u]=low[u]=++dfs_clock;
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]){//u为当前强连通分量的入口
scc_cnt++;
while(true){
int x=S.top(); S.pop();
sccno[x]=scc_cnt;
if(x==u) break;
}
}
}

//求出有向图所有连通分量
void find_scc(int n){
scc_cnt=dfs_clock=0;
memset(sccno,0,sizeof(sccno));
memset(pre,0,sizeof(pre));
for(int i=0;i<n;i++)
if(!pre[i]) dfs(i);
}
void work(int n,int m){
for(int i=0;i<n;i++) G[i].clear();
while(m--){
int u,v;
scanf("%d%d",&u,&v);//index range: 0~n-1
u--, v--;
G[u].push_back(v);
}
find_scc(n);
memset(in, false, sizeof(in));
memset(out, false, sizeof(in));
for (int i = 0; i<n; i++) {
for (int j=0; j<G[i].size(); j++) {
int v = G[i][j];
if (sccno[i]!=sccno[v]) {
in[sccno[v]] = true;
out[sccno[i]] = true;
}
}
}
int a = 0,b = 0;
for (int i = 1; i<=scc_cnt; i++) {
if (!in[i]) {
a++;
}
if (!out[i]) {
b++;
}
}
if (scc_cnt == 1) {
cout<<"0\n";
}
else
cout<<max(a, b)<<"\n";
}
int main(){
int n,m,T;
scanf("%d" ,&T);
while (T--) {
scanf("%d%d",&n,&m);
work(n,m);
}
return 0;
}