http://acm.hdu.edu.cn/showproblem.php?pid=4612
4 4 1 2 1 3 1 4 2 3 0 0
0
#pragma comment (linker, "/STACK:102400000,102400000")///手动扩栈 #include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <cmath> #include <cstdlib> #include <limits> #include <queue> #include <stack> #include <vector> #include <map> using namespace std; #define N 200005 #define INF 0xfffffff #define PI acos (-1.0) #define EPS 1e-8 vector <vector <int> > G1; vector <vector <int> > G2; int n, m, Time, cnt, top; int low[N], dfn[N], Stack[N], ft[N], f[N], step[N]; void Init (); void tarjan (int u, int fa); int BFS (int s, int flag); void solve (); int main () { while (scanf ("%d%d", &n, &m), n+m) { Init (); while (m--) { int a, b; scanf ("%d%d", &a, &b); G1[a].push_back (b); G1[b].push_back (a); } solve (); } return 0; } void Init () { G1.clear (); G1.resize (n+2); G2.clear (); G2.resize (n+2); memset (low, 0, sizeof (low)); memset (dfn, 0, sizeof (dfn)); memset (f, 0, sizeof (f)); memset (ft, 0, sizeof (ft)); memset (Stack, 0, sizeof (Stack)); Time = cnt = top = 0; } void tarjan (int u, int fa) { low[u] = dfn[u] = ++Time; Stack[top++] = u; f[u] = fa; int len = G1[u].size (), v, k = 0; for (int i=0; i<len; i++) { v = G1[u][i]; if (!k && v == fa) { k++; continue; } if (!low[v]) { tarjan (v, u); low[u] = min (low[u], low[v]); } else low[u] = min (low[u], dfn[v]); } if (low[u] == dfn[u]) { do { v = Stack[--top]; ft[v] = cnt; }while (u != v); cnt++; } } int BFS (int s, int flag) { int p, pn; queue <int> que; que.push (s); memset (step, -1, sizeof (step)); step[s] = 0; while (que.size ()) { p = que.front (); que.pop (); int len = G2[p].size (); for (int i=0; i<len; i++) { pn = G2[p][i]; if (step[pn] == -1) { step[pn] = step[p] + 1; que.push (pn); } } } if (flag == 1) return p; return step[p]; } void solve () { int ans = 0; for (int i=1; i<=n; i++) if (!low[i]) tarjan (i, i); for (int i=1; i<=n; i++) { int v = f[i]; if (ft[i] != ft[v]) {///重新构图 G2[ft[i]].push_back (ft[v]); G2[ft[v]].push_back (ft[i]); } } int p = BFS (0, 1);///以0为起点经行一次BFS返回最远距离的编号 ans = cnt - BFS (p, 2) - 1;///返回最远距离的长度 printf ("%d\n", ans); }