标签:
4 4 1 2 1 3 1 4 2 3 0 0
0
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <stack> #define maxn 200000+1000 #define maxm 2000000+1000 #pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; int n ,m; struct node { int u, v, next; }; node edge[maxm]; int head[maxn], cnt; int dfn[maxn], low[maxn]; int Stack[maxn], top; bool Instack[maxn]; int Belong[maxn]; int dfs_clock; int ebc_clock; int bridge; vector<int>Map[maxn]; int dist[maxn], vis[maxn]; int ans, nod; void init(){ cnt = 0; memset(head, -1, sizeof(head)); } void addedge(int u, int v){ edge[cnt] = {u, v, head[u]}; head[u] = cnt++; } void getmap(){ while(m--){ int a, b; scanf("%d%d", &a, &b); addedge(a, b); addedge(b, a); } } void tarjan(int u, int per){ int v; low[u] = dfn[u] = ++dfs_clock; Stack[top++] = u; Instack[u] = true; int have = 1; for(int i = head[u]; i != -1; i = edge[i].next){ v = edge[i].v; if(v == per && have){ have = 0; continue; } if(!dfn[v]){ tarjan(v, u); low[u] = min(low[u], low[v]); if(low[v] > dfn[u]) bridge++; } else if(Instack[v]) low[u] = min(low[u], dfn[v]); } if(dfn[u] == low[u]){ ebc_clock++; do{ v = Stack[--top]; Instack[v] = false; Belong[v] = ebc_clock; }while(v != u); } } void suodian(){//Ëõµã½¨ÐÂͼ for(int i = 1; i <= ebc_clock; ++i) Map[i].clear(); for(int i = 0; i < cnt; i = i + 2){ int u = Belong[edge[i].u]; int v = Belong[edge[i].v]; if(u != v){ Map[u].push_back(v); Map[v].push_back(u); } } } void find(){ memset(low, 0, sizeof(low)); memset(dfn, 0, sizeof(dfn)); memset(Instack, false, sizeof(Instack)); memset(Belong, 0, sizeof(Belong)); dfs_clock = ebc_clock = top = bridge = 0; for(int i = 1; i <= n; ++i){ if(!dfn[i]) tarjan(i, i); } } void BFS(int x){ queue<int>q; memset(vis, 0, sizeof(vis)); memset(dist, 0, sizeof(dist)); vis[x] = 1; ans = 0; nod = x; q.push(x); while(!q.empty()){ int u = q.front(); q.pop(); for(int i = 0; i < Map[u].size(); ++i){ int v = Map[u][i]; if(!vis[v]){ vis[v] = 1; dist[v] = dist[u] + 1; if(ans < dist[v]){ nod = v; ans = dist[v]; } q.push(v); } } } } int main (){ while(scanf("%d%d", &n, &m), n || m){ init(); getmap(); find(); suodian(); BFS(1); BFS(nod); printf("%d\n", bridge - ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 4612--Warm up 【无向图边双连通求桥数 && 缩点后重建图求树的直径】
标签:
原文地址:http://blog.csdn.net/hpuhjh/article/details/47760119