标签:
1 #include<cstdio> 2 #include<iostream> 3 #include<vector> 4 #include<cstring> 5 #include<string> 6 #include<stack> 7 #include<algorithm> 8 #include<map> 9 using namespace std; 10 11 struct Edge 12 { 13 int u,v; 14 }; 15 16 const int N=10005; 17 int dfn[N],low[N]; 18 int dfs_clock,m,n; 19 map<string,int>ver; 20 vector<int>G[N]; 21 vector<Edge>bridge; 22 vector<Edge>edges; 23 string guy[N]; 24 25 bool cmp(Edge a,Edge b) 26 { 27 if(a.u==b.u) 28 return a.v<b.v; 29 return a.u<b.u; 30 } 31 32 void init() 33 { 34 memset(low,0,sizeof(low)); 35 memset(dfn,0,sizeof(dfn)); 36 dfs_clock=0; 37 edges.clear(); 38 bridge.clear(); 39 ver.clear(); 40 for(int i=0;i<n;i++) 41 G[i].clear(); 42 } 43 44 int tarjan(int u,int fa) 45 { 46 int lowu=dfn[u]=++dfs_clock; 47 for(int i=0;i<G[u].size();i++) 48 { 49 int v=G[u][i]; 50 if(!dfn[v]) 51 { 52 int lowv=tarjan(v,u); 53 lowu=min(lowu,lowv); 54 } 55 else if(dfn[v]<dfn[u]&&v!=fa) 56 lowu=min(dfn[v],lowu); 57 } 58 low[u]=lowu; 59 return lowu; 60 } 61 62 int main() 63 { 64 int T; 65 scanf("%d",&T); 66 while(T--) 67 { 68 init(); 69 scanf("%d%d",&n,&m); 70 int num=0; 71 for(int i=0;i<m;i++) 72 { 73 string tmp1,tmp2; 74 int u,v; 75 cin>>tmp1>>tmp2; 76 if(!ver.count(tmp1)) 77 { 78 ver[tmp1]=num; 79 guy[num]=tmp1; 80 num++; 81 } 82 if(!ver.count(tmp2)) 83 { 84 ver[tmp2]=num; 85 guy[num]=tmp2; 86 num++; 87 } 88 u=ver[tmp1],v=ver[tmp2]; 89 edges.push_back((Edge){u,v}); 90 G[u].push_back(v); 91 G[v].push_back(u); 92 } 93 tarjan(0,-1); 94 int j=0; 95 for(j=0;j<n;j++) 96 if(!dfn[j])break; 97 if(j!=n) 98 printf("0\n"); 99 else 100 { 101 vector<Edge>::iterator it; 102 for(it=edges.begin();it!=edges.end();it++) 103 { 104 if(low[it->u]>dfn[it->v]||low[it->v]>dfn[it->u]) 105 bridge.push_back(*it); 106 } 107 printf("%d\n",bridge.size()); 108 sort(bridge.begin(),bridge.end(),cmp); 109 vector<Edge>::iterator iter; 110 for(iter=bridge.begin();iter!=bridge.end();iter++) 111 cout<<guy[iter->u]<<" "<<guy[iter->v]<<endl; 112 } 113 } 114 return 0; 115 }
标签:
原文地址:http://www.cnblogs.com/homura/p/4839110.html