给一个联通有向图,求两个值。
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;
}