A1122 Hamiltonian Cycle (25 point(s))

简单环判断

1. 原文

The “Hamilton cycle problem” is to find a simple cycle that contains every vertex in a graph. Such a cycle is called a “Hamiltonian cycle”.

In this problem, you are supposed to tell if a given cycle is a Hamiltonian cycle.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers N (2<N≤200), the number of vertices, and M, the number of edges in an undirected graph. Then M lines follow, each describes an edge in the format Vertex1 Vertex2, where the vertices are numbered from 1 to N. The next line gives a positive integer K which is the number of queries, followed by K lines of queries, each in the format:

n V1 V2 … Vn

where n is the number of vertices in the list, and Vi‘s are the vertices on a path.

output Specification:

For each query, print in a line YES if the path does form a Hamiltonian cycle, or NO if not.

Sample Input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
6 10
6 2
3 4
1 5
2 5
3 1
4 1
1 6
6 3
1 2
4 5
6
7 5 1 4 3 6 2 5
6 5 1 4 3 6 2
9 6 2 1 6 3 4 5 2 6
4 1 2 5 1
7 6 1 3 4 5 2 6
7 6 1 2 5 4 3 1

Sample output:

1
2
3
4
5
6
YES
NO
NO
NO
YES
NO

2. 解析

路径判断

1
if(graph[s][t]==Inf)

简单判断

1
if(visit[t]==true)

环判断

1
2
if(visit[i]==false)
if(start!=t)

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=210;
const int Inf=312312312;
int graph[maxn][maxn];
bool visit[maxn]={false};
int main()
{
fill(graph[0],graph[0]+maxn*maxn,Inf);
int n,m;
scanf("%d%d",&n,&m);
int a,b;
for (int i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
graph[a][b]=graph[b][a]=1;
}
int k;
scanf("%d",&k);
while(k--)
{
fill(visit,visit+maxn,false);
bool simple=true; bool cycle=true; bool connected=true;
int start,s,t; int a;
scanf("%d%d",&a,&s);
start=s;
for (int i = 1; i < a; ++i)
{
scanf("%d",&t);
if (visit[t]==true)
{
simple=false;
}
visit[t]=true;
if (graph[s][t]==Inf)
{
connected=false;
}
s=t;
}
for (int i = 1; i <= n; ++i)
{
if (visit[i]==false)
{
cycle=false;
}
}
//printf("%d %d %d %d\n", start!=t,!simple,!cycle,!connected);
if (start!=t||!simple||!cycle||!connected)
{
printf("NO\n");
}
else{
printf("YES\n");
}
}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1122/
  • 发布时间: 2019-09-03 08:34
  • 更新时间: 2021-10-29 14:08
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!