K圆

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

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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值