题目地址:http://acm.hust.edu.cn/vjudge/problem/20839
模板题,裸的算法
注意:
1)题中要求的桥 (u,v) u要小于v
2)图不一定连通,但图是无向的,且无重边
AC代码:
#include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100000+10;
typedef pair<int,int> Edge;
int id;
vector<bool> vis(maxn);
vector<int> dfn(maxn),low(maxn);
vector<vector<int> > G(maxn);
vector<Edge> bridge;
void Tarjan(int u,int father)
{dfn[u]=low[u]=++id;vis[u]=true;for(int i=0;i<G[u].size();i++){int v=G[u][i];if(!vis[v]){Tarjan(v,u);low[u]=min(low[u],low[v]);if(dfn[u]<low[v]) {if(u<v) bridge.push_back(Edge(u,v)); //注意u要小于v else bridge.push_back(Edge(v,u));}}else if(father!=v) //只能由非父子边更新 low[u]=min(low[u],dfn[v]);}
}
int main()
{int n,m,u,v;while(cin>>n){for(int i=0;i<n;i++) G[i].clear(),vis[i]=false;for(int i=0;i<n;i++){scanf("%d (%d)",&u,&m);while(m--){cin>>v;G[u].push_back(v);}}id=0; bridge.clear();for(int i=0;i<n;i++)if(!vis[i]) Tarjan(i,-1);printf("%d critical links\n",bridge.size());sort(bridge.begin(),bridge.end());for(int i=0;i<bridge.size();i++)printf("%d - %d\n",bridge[i].first,bridge[i].second);cout<<endl;}return 0;
}