给出一个N个点,M条边的图,现在希望我们将这样的一个图中所有边设定成单向边,问是否能够构成一个图,使得从u能够到v,也能够从v到u。
思路:
如果在有向图中,从u能到v,也能从v到u,那么如果我们将这样一个图变成无向图的话,我们直接跑边双联通其肯定分量数量为1的。
所以我们首先假定原图为无向图,然后跑一遍边双联通即可,如果其只包含一个分量,那么就是存在解,那么对应我们将原图随便Dfs一遍输出过程即可。
过程用map<pair,int>去重。
Ac代码:
#include<stdio.h>
#include<vector>
#include<string.h>
#include<map>
using namespace std;
map<pair<int,int>,int>s;
vector<int>mp[105000];
int n,m,sig,cnt,tt;
int xx[400000];
int yy[400000];
int dfn[150050];
int low[150050];
int vis[150050];
int stack[150050];
int color[150050];
void Tarjan(int u,int from)
{
vis[u]=1;
dfn[u]=low[u]=cnt++;
stack[++tt]=u;
for(int i=0;i<mp[u].size();i++)
{
int v=mp[u][i];
if(v==from)continue;
if(vis[v]==0)
{
Tarjan(v,u);
low[u]=min(low[u],low[v]);
}
else low[u]=min(low[u],low[v]);
}
if(low[u]==dfn[u])
{
sig++;
do
{
color[stack[tt]]=sig;
vis[stack[tt]]=-1;
}
while(stack[tt--]!=u);
}
}
void Dfs(int u,int from)
{
vis[u]=1;
for(int i=0;i<mp[u].size();i++)
{
int v=mp[u][i];
if(v==from)continue;
else if(vis[v]==0)
{
vis[v]=1;
s[make_pair(u,v)]=s[make_pair(v,u)]=1;
printf("%d %d\n",u,v);
Dfs(v,u);
}
else
{
if(s[make_pair(u,v)]==0)
{
s[make_pair(u,v)]=1;
s[make_pair(v,u)]=1;
printf("%d %d\n",u,v);
}
}
}
}
void Slove()
{
tt=-1;
cnt=1;
sig=0;
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(vis,0,sizeof(vis));
memset(stack,0,sizeof(stack));
memset(color,0,sizeof(color));
for(int i=1;i<=n;i++)
{
if(vis[i]==0)
{
Tarjan(i,-1);
}
}
if(sig>1)printf("0\n");
else
{
memset(vis,0,sizeof(vis));
Dfs(1,1);
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
s.clear();
for(int i=1;i<=n;i++)mp[i].clear();
for(int i=1;i<=m;i++)
{
int x,y;scanf("%d%d",&x,&y);
mp[x].push_back(y);
mp[y].push_back(x);
xx[i]=x;yy[i]=y;
}
Slove();
}
}