http://acm.hdu.edu.cn/showproblem.php?pid=3849
让求割边
如果图不连通,输出0
若联通,按顺序输出桥,这里利用了map,便于处理字符串
By Recognizing These Guys, We Find Social Networks UsefulTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)Total Submission(s): 4082 Accepted Submission(s): 1055 Problem Description Social Network is popular these days.The Network helps us know about those guys who we are following intensely and makes us keep up our pace with the trend of modern times. Input The input is a relation description map. Output In the first line,output an integer n,represents the number of key relations in the relation description map. Sample Input 1 4 4 saerdna aswmtjdsj aswmtjdsj mabodx mabodx biribiri aswmtjdsj biribiri Sample Output 1 saerdna aswmtjdsj |
#include<cstdio>
#include<cstring>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int maxn=10000+10;
const int maxm=100000+10;
int n,m;
struct node
{
char s[20];
bool operator <(const node& rhs)const
{
return strcmp(s,rhs.s)<0;
}
};
map<node,int> mp;//将字符串node映射成节点编号
struct Edge
{
node u,v;
bool flag;//标记该边是不是桥
} e[maxm];
vector<int> G[maxn];
int pre[maxn],low[maxn];
int dfs_clock;
void tarjan(int u,int fa)
{
low[u]=pre[u]=++dfs_clock;
for(int i=0; i<G[u].size(); i++)
{
int v=G[u][i];
if(v==fa) continue;
if(!pre[v])
{
tarjan(v,u);
low[u]=min(low[u],low[v]);
}
else low[u] = min(low[u],pre[v]);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int id=0;
scanf("%d%d",&n,&m);
mp.clear();
dfs_clock=0;
memset(pre,0,sizeof(pre));
for(int i=1; i<=n; i++) G[i].clear();
for(int i=0; i<m; i++)
{
e[i].flag=false;
scanf("%s%s",e[i].u.s,e[i].v.s);
if(mp.find(e[i].u)==mp.end()) mp[e[i].u]= ++id;
if(mp.find(e[i].v)==mp.end()) mp[e[i].v]= ++id;
int x = mp[e[i].u], y=mp[e[i].v];
G[x].push_back(y);
G[y].push_back(x);
}
tarjan(1,-1);
bool ok=true;//判断是否连通图
for(int i=1; i<=n; i++)if(!pre[i])
{
ok=false;
break;
}
if(!ok) printf("0\n");
else
{
int ans=0;//计数桥总数
for(int i=0; i<m; i++)
{
int u=mp[e[i].u], v=mp[e[i].v];
if(low[u]>pre[v]||low[v]>pre[u]) e[i].flag=true,ans++;
}
printf("%d\n",ans);
for(int i=0; i<m; i++)if(e[i].flag)
printf("%s %s\n",e[i].u.s,e[i].v.s);
}
}
return 0;
}