题意:在一张图中,让你求割边。并按照顺序数出来,注意图并不是连通的。
思路:对多个连通分支,每个执行一次dfs求割边。最后排序输出就好了。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cmath> 5 #include <cstring> 6 #include <algorithm> 7 #include <queue> 8 #include <stack> 9 #include <vector> 10 #define MP(a, b) make_pair(a, b) 11 #define PB(a) push_back(a) 12 13 using namespace std; 14 15 typedef long long ll; 16 typedef pair<int ,int> pii; 17 typedef pair<unsigned int, unsigned int> puu; 18 typedef pair<int ,double> pid; 19 typedef pair<ll, int> pli; 20 21 const int INF = 0x3f3f3f3f; 22 const double eps = 1e-6; 23 const int LEN = 1010; 24 struct Arc{ 25 int from, to; 26 }bri[LEN]; 27 int mp[LEN][LEN], n, nbri, low[LEN], dfn[LEN], dfs_clock, vis[LEN]; 28 vector<int> Map[LEN]; 29 inline bool cmp(Arc a, Arc b) 30 { 31 if(a.from != b.from) return a.from<b.from; 32 else return a.to<b.to; 33 } 34 35 36 //割边模版 37 //初始化 38 //for(int i=0; i<LEN; i++)Map[i].clear(); 39 //memset(vis, 0, sizeof vis); 40 void dfs(int u, int fa) 41 { 42 int v, i, son = 0; 43 vis[u] = 1; 44 dfn[u] = low[u] = dfs_clock++; 45 for(int i = 0; i < Map[u].size(); i++){ 46 v = Map[u][i]; 47 if(vis[v] == 1 && v != fa)low[u] = min(low[u], low[v]); 48 if(vis[v] == 0){ 49 dfs(v, u); 50 son++; 51 low[u] = min(low[u], low[v]); 52 if(low[v] > dfn[u])bri[nbri].from = min(u, v), bri[nbri++].to = max(v, u); 53 } 54 } 55 } 56 57 int main() 58 { 59 // freopen("in.txt", "r", stdin); 60 61 int from, to, tn; 62 while(scanf("%d", &n)!=EOF) 63 { 64 memset(mp, 0 ,sizeof mp); 65 for(int i=0; i<LEN; i++)Map[i].clear(); 66 memset(vis, 0, sizeof vis); 67 dfs_clock = 0, nbri = 0; 68 for(int i=0; i<n; i++){ 69 scanf("%d (%d)", &from, &tn); 70 for(int j=0; j<tn; j++){ 71 scanf("%d", &to); 72 if(!mp[from][to]){ 73 mp[from][to] = mp[to][from] = 1; 74 Map[from].PB(to); 75 Map[to].PB(from); 76 } 77 } 78 } 79 for(int i=0; i<n; i++){ 80 if(vis[i]==0){ 81 dfs(i, -1); 82 } 83 } 84 sort(bri, bri+nbri, cmp); 85 printf("%d critical links\n", nbri); 86 for(int i=0; i<nbri; i++) printf("%d - %d\n", bri[i].from, bri[i].to); 87 printf("\n"); 88 } 89 return 0; 90 }