http://acm.hdu.edu.cn/showproblem.php?pid=3836
题意:给一个有向图,问最少需要添加多少条边使之成为强连通图。
显然能够想到用Tarjan缩点,然后怎么求对于剩余图最少需要加几条边呢。
要使缩点后的图成为强连通图,每个顶点最少要有一个入度和一个出度,一条边又提供一个出度和一个入度。所以可以通过统计没有入度的顶点数
ans1
a
n
s
1
和没有出度的顶点数
ans2
a
n
s
2
。
所需要添加的边数就是
max(ans1,ans2)
max
(
a
n
s
1
,
a
n
s
2
)
。
#include<iostream>
#include<cstdio>
#include<stack>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
using namespace std;
const int maxn=50010,maxm=50010;
int dfn[maxn],low[maxn],head1[maxn],head2[maxn],color[maxn],sum[maxn],dis[maxn],r[maxn],c[maxn];
int n,m,k,cnt,deep,ans1,ans2;
bool vis[maxn];
struct edge{
int v,w,next;
}e1[maxm],e2[maxm];
stack<int> st;
void addedge1(int u,int v){e1[k].v=v;e1[k].next=head1[u];head1[u]=k++;}
void addedge2(int u,int v,int w){e2[k].v=v;e2[k].w=w;e2[k].next=head2[u];head2[u]=k++;}
void tarjan(int u)
{
deep++;
dfn[u]=deep;
low[u]=deep;
vis[u]=1;
st.push(u);
for(int i=head1[u];~i;i=e1[i].next)
{
int v=e1[i].v;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else
{
if(vis[v])
{
low[u]=min(low[u],low[v]);
}
}
}
if(dfn[u]==low[u])
{
cnt++;
color[u]=cnt;
vis[u]=0;
while(st.top()!=u)
{
color[st.top()]=cnt;
vis[st.top()]=0;
st.pop();
}
st.pop();
}
}
int main()
{
int x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
cnt=0,ans1=0,ans2=0;
k=0;
memset(head1,-1,sizeof(head1));
memset(head2,-1,sizeof(head2));
memset(dfn,0,sizeof(dfn));
memset(r,0,sizeof(r));
memset(c,0,sizeof(c));
memset(vis,0,sizeof(vis));
st=stack<int>();
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
addedge1(x,y);
}
for(int i=1;i<=n;i++)
{
if(!dfn[i])
tarjan(i);
}
k=0;
for(int i=1;i<=n;i++)
{
for(int j=head1[i];~j;j=e1[j].next)
{
if(color[i]!=color[e1[j].v])
{
addedge2(color[i],color[e1[j].v],1);
r[color[e1[j].v]]++;
c[color[i]]++;
}
}
}
if(cnt==1)
{
printf("0\n");
continue;
}
for(int i=1;i<=cnt;i++)
{
if(r[i]==0)
ans1++;
if(c[i]==0)
ans2++;
}
printf("%d\n",max(ans1,ans2));
}
return 0;
}