UVA12167 Proving Equivalences

传说中的链接

这道题,建图灰常的好建,就是把命题当成点,把证明关系当成有向边,求得就是最少加多少条边,使得整个图强连通。求一个强连通分量,然后答案就是出度为零的点和入度为零的点的最大值,因为只有出度或入度为零的点都连上边才能保证整个图都是强联通的。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
const int N = 22222;
int pre[N], lowlink[N], sccno[N], dfs_clock, scc_cnt, n, m;
int in0[N], out0[N];
vector<int> G[N];
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 (!pre[v]){
			dfs(v);
			lowlink[u] = min(lowlink[u], lowlink[v]);
		}
		else if (!sccno[v]){
			lowlink[u] = min(lowlink[u], pre[v]);
		}
	}
	if (lowlink[u] == pre[u]){
		scc_cnt += 1;
		for (; ;){
			int x = S.top(); S.pop();
			sccno[x] = scc_cnt;
			if (x == u) break;
		}
	}
}
void tarjan(int n){
	dfs_clock = scc_cnt = 0;
	memset(sccno, 0, sizeof(sccno));
	memset(pre, 0, sizeof(pre));
	for (int i = 0; i < n; i++)
		if (!pre[i]) dfs(i);
}
int main(){
	int cs; scanf("%d", &cs);
	while(cs--){
		scanf("%d%d", &n, &m);
		for (int i = 0; i <= n; i++)
			G[i].clear();
		int x, y;
		for (int i = 0; i < m; i++){
			scanf("%d%d", &x, &y);
			x -= 1; y -= 1;
			G[x].push_back(y);
		}
		tarjan(n);
		for (int i = 1; i <= scc_cnt; i++)
			in0[i] = out0[i] = 1;
		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]) in0[sccno[v]] = out0[sccno[u]] = 0;
			}
		int a = 0, b = 0;
		for (int i = 1; i <= scc_cnt; i++){
			if (in0[i]) a += 1;
			if (out0[i]) b += 1;
		}
		int ans = max(a, b);
		if (scc_cnt == 1) ans = 0;
		printf("%d\n", ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值