poj 1236

给一个联通有向图,求两个值。
1.从多少个点出发能遍历所有的点
2.加多少条边使得整个图是强联通的。

缩点以后可知问题1的解就是图中入度为0的点的个数,对于问题2,答案为max(num(ind=0),num(outd=0),可以把入度和出度为0的点对应连起来,然后如果入度为0>出度为0,就从已经和出度为0连过的入度为0的点加一条边即可。反之亦然。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define f first
#define s second
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
const int N = 100 + 10;
const int M = 10000 + 10;
int h[N],nt[M],to[M],cnt;
int n,scc[N],sc,dfn[N],low[N];
int dfs_clock,in[N],out[N];
int stk[N],top;
void tarjan(int u){
	dfn[u] = low[u] = ++dfs_clock;
	stk[++top] = u;
	for(int i = h[u] ; i ; i = nt[i]){
		int v = to[i];
		if(!dfn[v]) tarjan(v),low[u] = min(low[u],low[v]);
		else if(!scc[v]) low[u] = min(low[u],dfn[v]);
	}
	if(dfn[u] == low[u]) {
		++sc;
		while(1){
			int x = stk[top--];
			scc[x] = sc;
			if(x == u) break;
		}
	}
}
void add(int u,int v){
	to[++cnt] = v;
	nt[cnt] = h[u];
	h[u] = cnt;
}
int main(){
	//ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	scanf("%d",&n);
	for(int i = 1; i <= n; i++) {
		int x ; 
		while(scanf("%d",&x) && x) {
			add(i, x);
		}
	}
	for(int i = 1; i <= n; i++) 
		if(!dfn[i]) tarjan(i);
	//for(int i = 1; i <= n; i++) cout<<scc[i]<<' ';cout<<endl;
	for(int i = 1; i <= n ;i++) {
		for(int j = h[i] ; j ;j = nt[j]){
			int t = to[j];
			if(scc[i] != scc[t]) {
				in[scc[t]]++;
				out[scc[i]]++;
			}
		}
	}
	int ans1 = 0 , ans2 = 0 ;
	for(int i = 1 ; i <= sc ; i++) {
		if(!in[i]) ans1++;
		if(!out[i]) ans2++;
	}
	if(sc == 1) printf("1\n0\n");
	else printf("%d\n%d\n",ans1,max(ans1,ans2));
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值