Problem Description
A single cycle is a closed simple path, with no other repeated vertices or edges other than the starting and ending vertices. The length of a cycle is the number of vertices on it. Given an undirected graph G(V,E), you're to detect whether it contains a simple cycle of length K. To make the problem easier, we only consider cases with small K here.
Input
On the first line of input, there is a single positive integer T<=10 specifying the number of test cases followed.
For each test case, the first line contains three positive integers N,M and K(N<=50,M<=500 and 3<=K<=7). Here N is the number of vertices of the graph, M is the number of edges and K is the length of the cycle desired. Next follow M lines, each with 2 integers A and B, describing an undirected edge AB of the graph. Vertices are numbered from 0 to N-1.
Output
For each test case, you should output "YES" in one line if there's a cycle of length K in the given grath, otherwise output "NO".
Sample Input
2
6 8 4
0 1
1 2
2 0
3 4
4 5
5 3
1 3
2 4
4 4 3
0 1
1 2
2 3
3 0
Sample Output
YES
A single cycle is a closed simple path, with no other repeated vertices or edges other than the starting and ending vertices. The length of a cycle is the number of vertices on it. Given an undirected graph G(V,E), you're to detect whether it contains a simple cycle of length K. To make the problem easier, we only consider cases with small K here.
Input
On the first line of input, there is a single positive integer T<=10 specifying the number of test cases followed.
For each test case, the first line contains three positive integers N,M and K(N<=50,M<=500 and 3<=K<=7). Here N is the number of vertices of the graph, M is the number of edges and K is the length of the cycle desired. Next follow M lines, each with 2 integers A and B, describing an undirected edge AB of the graph. Vertices are numbered from 0 to N-1.
Output
For each test case, you should output "YES" in one line if there's a cycle of length K in the given grath, otherwise output "NO".
Sample Input
2
6 8 4
0 1
1 2
2 0
3 4
4 5
5 3
1 3
2 4
4 4 3
0 1
1 2
2 3
3 0
Sample Output
YES
NO
#include<stdio.h>
#include<string.h>
#include<iostream>
#define Max 55
using namespace std;
int m,n,k,flag,xx;
int v_p[Max],v_e[Max][Max];
int vis[Max];
void dfs(int x,int cnt)
{
if(flag) return;
int i;
if(cnt==k-1)
{
for(i=1;i<=v_p[x];i++)
if(v_e[x][i]==xx)
flag=1;
return;
}
for(i=1;i<=v_p[x];i++)
{
if(!vis[v_e[x][i]])
{
vis[v_e[x][i]]=1;
dfs(v_e[x][i],cnt+1);
}
}
}
int main()
{
//freopen("b.txt","r",stdin);
int t,a,b;
scanf("%d",&t);
while(t--)
{
flag=0;
scanf("%d %d %d",&m,&n,&k);
memset(v_p,0,sizeof(v_p));
memset(v_e,0,sizeof(v_e));
while(n--)
{
scanf("%d %d",&a,&b);
v_e[a][++v_p[a]]=b;
v_e[b][++v_p[b]]=a;
}
for(xx=0;xx<m;xx++)
{
memset(vis,0,sizeof(vis));
vis[xx]=1;
dfs(xx,0);
if(flag) break;
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}