Uva796 Critical Links
用tarjan缩点
然后用dfn[u] < low[v]缩点并且保存起来
在sort一遍输出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 5 using namespace std; 6 7 const int maxn = 10000; 8 9 struct Node { 10 int u; 11 int v; 12 int next; 13 }; 14 struct Edge{ 15 int u; 16 int v; 17 }; 18 Edge edge[maxn]; 19 Node node[maxn * 10]; 20 int head[maxn]; 21 int dfn[maxn]; 22 int low[maxn]; 23 int fath[maxn]; 24 bool vis[maxn]; 25 bool maps[maxn][maxn]; 26 int n, tol, cnt; 27 28 void init() { 29 cnt = tol= 0; 30 memset(dfn, 0, sizeof(dfn)); 31 memset(low, 0, sizeof(low)); 32 memset(maps, 0, sizeof(maps)); 33 memset(fath, 0, sizeof(fath)); 34 memset(head, -1, sizeof(head)); 35 memset(vis, false, sizeof(vis)); 36 } 37 38 void addnode(int u, int v) { 39 node[tol].u = u; 40 node[tol].v = v; 41 node[tol].next = head[u]; 42 head[u] = tol++; 43 } 44 45 void dfs(int u, int fa){ 46 fath[u] = fa; 47 low[u] = dfn[u] = ++cnt; 48 vis[u] = true; 49 for(int i=head[u]; i!=-1; i=node[i].next) { 50 int v = node[i].v; 51 if(!dfn[v]) { 52 dfs(v, u); 53 low[u] = min(low[u], low[v]); 54 } else if(v != fa) { 55 low[u] = min(low[u], dfn[v]); 56 } 57 } 58 } 59 60 void tarjan() { 61 for(int u=0; u<n; u++) { 62 if(!dfn[u]) { 63 dfs(u, u); 64 } 65 } 66 } 67 68 bool cmp(Edge a, Edge b) { 69 if(a.u == b.u) 70 return a.v < b.v; 71 else 72 return a.u < b.u; 73 } 74 75 void solve() { 76 tol = 0; 77 for(int u=0; u<n; u++) { 78 int v = fath[u]; 79 if(low[u] > dfn[v] && v != u) { 80 edge[tol].u = u; 81 edge[tol].v = v; 82 if(edge[tol].u > edge[tol].v) 83 swap(edge[tol].u, edge[tol].v); 84 tol++; 85 } 86 } 87 sort(edge, edge+tol, cmp); 88 printf("%d critical links\n", tol); 89 for(int i=0; i<tol; i++) { 90 printf("%d - %d\n", edge[i].u, edge[i].v); 91 } 92 printf("\n"); 93 } 94 95 int main() { 96 while(scanf("%d", &n) != EOF) { 97 init(); 98 if(n == 0) { 99 printf("0 critical links\n\n"); 100 continue; 101 } 102 for(int i=1; i<=n; i++) { 103 int u; 104 int num; 105 scanf("%d (%d)", &u, &num); 106 for(int j=1; j<=num; j++) { 107 int v; 108 scanf("%d", &v); 109 maps[u][v] = maps[v][u] = 1; 110 } 111 } 112 for(int i=0; i<n; i++) { 113 for(int j=i+1; j<n; j++) { 114 if(maps[i][j]) { 115 addnode(i, j); 116 addnode(j, i); 117 } 118 } 119 } 120 tarjan(); 121 solve(); 122 } 123 return 0; 124 }