Uvalive 4287 - Proving Equivalences(强联通分量)
题目链接 https://vjudge.net/problem/UVALive-4287
【题意】
在数学中,我们常常需要完成若干个命题的等价性证明,比如4个命题a,b,c,d.我们证明a<->b,b<->c,c<->d,每次证明都是双向的,因此一共完成了6次推导。另外一种证明方法是a->b,b->c,c->d,d->a,只需4次。现在要证明n个命题等价,并且已经有了m个已知的推导过程,那么至少还需要多少次推导才能完成证明?
【思路】
把命题看成点,推导关系看成有向边,问题转换成了给出n个结点和m条边的有向图,要求加尽量少的边,使得新图强连通。那么我们可以先求出原图中的强连通分量,然后把每一个连通分量缩成一个点,形成一个DAG,那么这个DAG中假设入度为0的点的个数是c1,出度为0的点的个数是c2,答案便是max(c1,c2),当原图本身就是强联通时,答案是0。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 20050;
const int maxm = 50050;
int n, m;
int dfs_clock, scc_cnt;
int pre[maxn], lowlink[maxn], sccno[maxn];
int inDegree[maxn], outDegree[maxn];
vector<int> g[maxn];
stack<int> s;
void dfs(int u) {
pre[u] = lowlink[u] = ++dfs_clock;
s.push(u);
for (int i = 0; i < g[u].size(); ++i) {
int v = g[u][i];
if (0 == pre[v]) {
dfs(v);
lowlink[u] = min(lowlink[u], lowlink[v]);
}
else if (0 == sccno[v]) {
lowlink[u] = min(lowlink[u], pre[v]);
}
}
if (lowlink[u] == pre[u]) {
++scc_cnt;
while (1) {
int x = s.top();
s.pop();
sccno[x] = scc_cnt;
if (x == u) break;
}
}
}
void find_scc(int n) {
dfs_clock = scc_cnt = 0;
memset(pre, 0, sizeof(pre));
memset(sccno, 0, sizeof(sccno));
for (int i = 0; i < n; ++i) {
if (0 == pre[i]) dfs(i);
}
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; ++i) g[i].clear();
for (int i = 0; i < m; ++i) {
int from, to;
scanf("%d%d", &from, &to);
--from, --to;
g[from].push_back(to);
}
find_scc(n);
for (int i = 1; i <= scc_cnt; ++i) {//入度,出度初始化为0
inDegree[i] = outDegree[i] = 0;
}
for (int u = 0; u < n; ++u) {
for (int i = 0; i < g[u].size(); ++i) {
int v = g[u][i];
if (sccno[u] != sccno[v]) {
outDegree[sccno[u]] = inDegree[sccno[v]] = 1;
//编号为sccno[u]的强连通分量指向了编号为sccno[v]的强连通分量
}
}
}
int c1 = 0, c2 = 0;
for (int i = 1; i <= scc_cnt; ++i) {
if (0 == inDegree[i]) ++c1;
if (0 == outDegree[i]) ++c2;
}
int ans = max(c1, c2);
if (scc_cnt == 1) ans = 0;
printf("%d\n", ans);
}
return 0;
}