Network of Schools POJ - 1236
题意:
给你一个有向图。
叫你求ans1:
最少的点,使得所有图内所有的点都可以接收到消息的传递。
叫你求ans2:
加最少的边,使得整个图变为强联通。
思路:
- 先用tarjan缩点
- 对于ans1:那么问题就转换成了求有多少个强联通块为0.
- 对于ans2:这么多强联通块, 把这些整合成一个大的联通块。
可以由图中可以得到
a
n
s
2
=
m
a
x
(
c
n
t
1
,
c
n
t
2
)
ans2=max(cnt1,cnt2)
ans2=max(cnt1,cnt2)
cnt1 统计入度为0,cnt2统计出度为0.
AC
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define mst(x,a) memset(x,a,sizeof(x))
#define fzhead EDGE(int _to, int _next)
#define fzbody to(_to), next(_next)
#pragma comment(linker,"/STACK:102400000,102400000")
using namespace std;
const int maxn=1e4+10;
int n,m,dfs_clock;
int head[maxn];
int tot;
struct EDGE{
int to, next;
EDGE(){}
fzhead:fzbody{}
}e[maxn*6];
int pre[maxn],low[maxn],vis[maxn],dfn[maxn],col[maxn],num[maxn];
int bcc_cnt;
int bridge[maxn*6];
int dep[maxn];
int in[maxn],out[maxn];
stack<int> s;
void init(){
tot=dfs_clock=bcc_cnt=0;
mst(head,-1);
mst(dfn,0);
mst(pre,0);
mst(vis,0);
mst(bridge,0);
mst(in,0);
mst(out,0);
mst(num,0);
mst(col,0);
while(!s.empty())s.pop();
}
void add(int bg, int to){
e[tot]=EDGE(to,head[bg]);
head[bg]=tot++;
}
void tarjan(int u, int f){
vis[u]=1;
dfn[u]=low[u]=++dfs_clock;
s.push(u);
for(int i=head[u]; i!=-1; i=e[i].next){
int v = e[i].to;
if(!dfn[v]){
pre[v]=(i^1);
tarjan(v,u);
low[u]=min(low[u],low[v]);
}else if(vis[v])low[u]=min(low[u],dfn[v]);
///if(v!=f&&dfn[v]<dfn[u])low[u]=min(low[u],dfn[v]);
///当前结点有向上连的边。
}
if(dfn[u]==low[u]){
col[u] = ++bcc_cnt;//num[bcc_cnt]++;
vis[u] = 0;
int j;
bridge[pre[u]]=1;
bridge[pre[u]^1]=1;
do{
j=s.top();s.pop();
col[j] = bcc_cnt;
num[bcc_cnt]++;
}while(j!=u);
}
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
init();tot=2;///most important
int u,v;
for(int i=1; i<=n; i++){
u=i;
while(cin>>v,v)add(u,v);//,add(v,u);
}
For(i,1,n)if (!dfn[i])dfs_clock=0,tarjan(i,0);//if(!pre[i])tarjan(i,0);
For(u,1,n){
for(int i=head[u]; i!=-1; i=e[i].next){
int v=e[i].to;
if(col[u]!=col[v])out[col[u]]++,in[col[v]]++;
}
}
int ans1=0;
For(color,1,bcc_cnt)if(in[color]==0)ans1++;
int tmpa=0,tmpb=0;
if(bcc_cnt==1){
cout<<1<<endl<<0<<endl;
return 0;
}
For(color,1,bcc_cnt){
if(in[color]==0)tmpa++;
if(out[color]==0)tmpb++;
}
cout<<ans1<<endl;
cout<<max(tmpa,tmpb)<<endl;
return 0;
}