题目
题意:求解将一个图变成强连通图需要添加的最小边数
思路:首先用tarjan将图缩点变成DAG,既然是强连通图,那么每个点都应该能进也能出,所以统计一下出度,入度为0的点的数量,要求边数最少,所以取max(innum,outnum)作为答案;
#include<bits/stdc++.h>
#include<map>
const int maxn = 3e4 + 10;
using namespace std;
int n,m,dfn[maxn],head[maxn],low[maxn],vis[maxn],stk[maxn],top,cnt,index,ans,scc,belong[maxn],in[maxn],out[maxn];
struct EDG {
int v,nxt;
}edge[60000 + 10];
void Initial() {
top = cnt = index = ans = scc = 0;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
memset(dfn,0,sizeof(dfn));
memset(belong,0,sizeof(belong));
memset(out,0,sizeof(out));
memset(in,0,sizeof(in));
}
void add_edge(int u,int v) {
edge[cnt].v = v;
edge[cnt].nxt = head[u];
head[u] = cnt++;
}
void tarjan(int u) {
dfn[u] = low[u] = ++index;
stk[top++] = u;
vis[u] = 1;
int v;
for(int i = head[u]; ~i; i=edge[i].nxt) {
v = edge[i].v;
if(!dfn[v]) {
tarjan(v);
low[u] = min(low[v],low[u]);
}else if(vis[v]) {
low[u] = min(low[u],dfn[v]);
}
}
if(dfn[u] == low[u]) {
scc++;
do {
v = stk[--top];
belong[v] = scc;
vis[v] = 0;
}while(v != u);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&n,&m);
Initial();
for(int i = 1;i <= m; ++i) {
int u,v;
scanf("%d%d",&u,&v);
add_edge(u,v);
}
for(int i = 1;i <= n; ++i) {
if(!dfn[i]) {
tarjan(i);
}
}
for(int i = 1;i <= n; i++) {
for(int j = head[i];~j;j = edge[j].nxt) {
int v = edge[j].v;
if(belong[i] != belong[v]) {
out[belong[i]]++;
in[belong[v]]++;
}
}
}
int inn = 0,outn = 0;
for(int i = 1;i <= scc; ++i) {
if(in[i] == 0) inn++;
if(out[i] == 0) outn++;
}
if(scc == 1) cout<<0<<endl;
else cout<<max(inn,outn)<<endl;
}
return 0;
}
Alstein
发布了42 篇原创文章 · 获赞 27 · 访问量 7617
私信
关注