K圆
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 22 Accepted Submission(s) : 8
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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.
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
Author
//题意是说在无向图中判断是否存在环并且它的顶点数刚好等于k。
题解:用邻接表存储边的关系,从第0-n枚举每个顶点,深度优先遍历整个图,如果在第k个点刚好等于初始点,则置标记,退出。
#include<cstdio>
#include<cstring>
#define N 55
int n,m,k,xx,flag,map[N][N],vis[N];
void dfs(int x,int cnt) //x表示顶点,cnt表示顶点数
{
if(flag) return; //剪枝 找到就退出
if(cnt==k-1) //如果第k个点刚好等于出发点,就标记
{
for(int i=1;i<=map[x][0];i++)
if(map[x][i]==xx)
flag=1;
return;
}
for(int i=1;i<=map[x][0];i++)
{
if(!vis[map[x][i]])
{
vis[map[x][i]]=1;
dfs(map[x][i],cnt+1);
}
}
}
int main()
{
int t,a,b;
scanf("%d",&t);
while(t--)
{
flag=0;
memset(map,0,sizeof(map));
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=m;i++) //邻接表
{
scanf("%d%d",&a,&b);
map[a][++map[a][0]]=b;
map[b][++map[b][0]]=a;
}
for(xx=0;xx<n;xx++) //枚举每个初始点
{
memset(vis,0,sizeof(vis)); //初始为0
vis[xx]=1;
dfs(xx,0);
if(flag) break;
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}