PAT-A1122 Hamiltonian Cycle 题目内容及题解

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 V​1​​ V​2​​ ... V​n​​

where n is the number of vertices in the list, and V​i​​'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:

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:

YES
NO
NO
NO
YES
NO

题目大意

题目给定一个无向图,和一个请求序列。题目要求判断每个请求序列中的顶点是否构成一个哈密顿环(一个包含图中每个顶点的简单循环),并输出结果。

解题思路

  1. 初始化并读入无向图;
  2. 对每个请求序列初始化vis数组,读入序列,判断是否可能成环(首尾是否一致,节点是否符合),通过上一步后依次判断每个节点是否读入过,相邻节点间是否存在路径等,并将结果输出;
  3. 返回零值。

代码

#include
#define maxn 210

int G[maxn][maxn],N,M,K;

void Init(){
    int a,b;
    scanf("%d%d",&N,&M);
    while(M--){
        scanf("%d%d",&a,&b);
        G[a][b]=1;
        G[b][a]=1;
    }
    scanf("%d",&K);
}

void Check(){
    int n,i;
    int seq[maxn],vis[maxn];
    scanf("%d",&n);
    for(i=0;i

运行结果

PAT-A1122 Hamiltonian Cycle 题目内容及题解_第1张图片

 

你可能感兴趣的:(PAT甲级)