Cycles of Lanes
Description Each of the M lanes of the Park of Polytechnic University of Bucharest connects two of the N crossroads of the park (labeled from 1 to N). There is no pair of crossroads connected by more than one lane and it is possible to pass from each crossroad to each other crossroad by a path composed of one or more lanes. A cycle of lanes is simple when passes through each of its crossroads exactly once. Input On the first line of the input file the number T of the test cases will be given. Each test case starts with a line with the positive integers N and M, separated by interval (4 <= N <= 4444). Each of the next M lines of the test case contains the labels of one of the pairs of crossroads connected by a lane. Output For each of the test cases, on a single line of the output, print the length of a maximal simple cycle. Sample Input Sample Output Source |
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=10010;
vector<int> v[maxn];
bool vis[maxn];
int ans;
int step[maxn];//记录搜索到某顶点时已搜索过的顶点数
void dfs( int x, int t)
{
vis[x]=1;
step[x]=t;//搜索到x时,已搜索过的顶点数
for(size_t i=0; i<v[x].size(); i++)
{
if(!vis[v[x][i]])//没有发现环
dfs(v[x][i],t+1);
else//发现环
ans=max(ans,step[v[x][i]]-step[x]+1);
}
}
int main()
{
int n,m,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
{
v[i].clear();
}
memset(vis,0,sizeof(vis));
memset(step,0,sizeof(step));
ans=0;
while(m--)
{
int l,r;
scanf("%d%d",&l,&r);
v[l].push_back(r);
v[r].push_back(l);
}
for(int i=1; i<=n; i++)
{
if(!vis[i])
dfs(i,1);
}
printf("%d\n",ans);
}
return 0;
}