https://vjudge.net/problem/UVALive-4287
题意:
给出n个结点m条边的有向图,要求加尽量少的边,使得新图强连通。
思路:
强连通分量缩点,然后统计缩点后的图的每个结点是否还需要出度和入度。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
typedef pair<int,ll> pll;
const int INF = 0x3f3f3f3f;
const int maxn=+; int n, m;
int tot;
int dfs_clock;
int scc_cnt;
int in[maxn];
int out[maxn];
int pre[maxn];
int head[maxn];
int sccno[maxn];
int lowlink[maxn]; stack<int> S; struct node
{
int v;
int next;
}e[+]; void addEdge(int u, int v)
{
e[tot].v=v;
e[tot].next=head[u];
head[u]=tot++;
} void dfs(int u)
{
pre[u]=lowlink[u]=++dfs_clock;
S.push(u);
for(int i=head[u];i!=-;i=e[i].next)
{
int v=e[i].v;
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++;
for(;;)
{
int x=S.top();S.pop();
sccno[x]=scc_cnt;
if(x==u) break;
}
}
} void find_scc()
{
dfs_clock=scc_cnt=;
memset(sccno,,sizeof(sccno));
memset(pre,,sizeof(pre));
for(int i=;i<=n;i++)
{
if(!pre[i]) dfs(i);
}
} int main()
{
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
tot=;
memset(head,-,sizeof(head));
while(m--)
{
int u,v;
scanf("%d%d",&u,&v);
addEdge(u,v);
}
find_scc();
for(int i=;i<=scc_cnt;i++) in[i]=out[i]=;
for(int u=;u<=n;u++)
{
for(int i=head[u];i!=-;i=e[i].next)
{
int v=e[i].v;
if(sccno[u]!=sccno[v]) in[sccno[v]]=out[sccno[u]]=; //u,v是桥,所以v不需要入度,u不需要出度
}
} int a=,b=;
for(int i=;i<=scc_cnt;i++)
{
if(in[i]) a++;
if(out[i]) b++;
}
int ans=max(a,b);
if(scc_cnt==) ans=;
printf("%d\n",ans);
}
return ;
}