题目链接;http://acm.hdu.edu.cn/showproblem.php?pid=3849
无向图求割边(Tarjan):
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;
#define Maxn 10005
#define Maxm 400100
struct Edge
{
int a,b;
}edge[Maxm];
int first[Maxn];
bool iscut[Maxm];
bool isused[Maxm];
int next[Maxm];
int total;
int dfn[Maxn];
int low[Maxn];
int dfs_clock;
int n,m;
map <string,int> ma;
void addEdge(int a,int b)
{
edge[total].a = a;edge[total].b = b;
next[total] = first[a];
first[a] = total;
total++;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++dfs_clock;
for(int i=first[u];i!=-1;i=next[i])
{
if(isused[i] == false)
{
isused[i^1] = isused[i] = true;
int v = edge[i].b;
if(!dfn[v])
{
tarjan(v);
low[u] = min(low[u],low[v]);
}
else
{
low[u] = min(low[u],dfn[v]);
}
if (dfn[u] < low[v])
{
iscut[i^1] = iscut[i] = true;
}
}
}
}
void cutLine(int n)
{
dfs_clock = 0;
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(iscut,false,sizeof(iscut));
memset(isused,false,sizeof(isused));
//如果是连通图,tarjan(1)就够了
tarjan(1);
//如果是非连通图
/*for(int i=1;i<=n;i++)
{
if(!dfn[i]) tarjan(i);
}*/
}
void init()
{
memset(first,-1,sizeof(first));
memset(next,-1,sizeof(next));
total = 0;
}
char tF[100005][20];
char tL[100005][20];
char temp1[20],temp2[20];
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int t;
int num = 0;
scanf(" %d",&t);
while(t--)
{
ma.clear();
num = 0;
init();
scanf(" %d %d ",&n,&m);
for(int i=0;i<m;i++)
{
scanf(" %s %s",temp1,temp2);
strcpy(tF[i],temp1);
strcpy(tL[i],temp2);
if(ma.find(temp1) == ma.end()) ma[temp1] = ++num;
if(ma.find(temp2) == ma.end()) ma[temp2] = ++num;
addEdge(ma[temp1],ma[temp2]);
addEdge(ma[temp2],ma[temp1]);
}
cutLine(n);
int flag = 0;
for(int i=1;i<=n;i++)
{
if(dfn[i] == 0)
{
printf("0\n");
flag = 1;
break;
}
}
if(flag == 1) continue;
int ans = 0;
for(int i=0;i<2*m;i+=2)
{
if(iscut[i]) ans++;
}
printf("%d\n",ans);
for(int i=0;i<2*m;i+=2)
{
if(iscut[i])
{
printf("%s ",tF[i/2]);
printf("%s\n",tL[i/2]);
}
}
}
return 0;
}