http://poj.org/problem?id=3895
技巧是标记每个节点的步数和是否访问过
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string.h>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
#define LL long long
#define pi acos(-1)
#define N 5000
#define INF 999999999
#define eps 1e-8
//****************************************
//poj 3895 无向图最大环
//Copyright@leolin All rights reserved.
//****************************************
vector<int> v[N];
int vis[N];
int step[N];
int ans;
void dfs(int x,int t)
{
vis[x]=1;
step[x]=t;
int i;
for(i=0;i<v[x].size();i++)
{
int k=v[x][i];
if(!vis[k])
dfs(k,t+1);
else
{
int temp=step[x]-step[k]+1;
if(temp>ans)ans=temp;
}
}
}
int main()
{
int ca;
scanf("%d",&ca);
int n,m;
while(ca--)
{
scanf("%d%d",&n,&m);
int i,j,k;
for(i=0;i<=n;i++)
{
vis[i]=0;
v[i].clear();
}
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
v[a].push_back(b);
v[b].push_back(a);
}
ans=0;
for(i=1;i<=n;i++)
{
if(!vis[i])
{
dfs(i,1);
}
}
if(ans>=3)
printf("%d\n",ans);
else
printf("0\n");
}
return 0;
}