当前位置: 代码迷 >> 综合 >> PAT - 甲级 - 1122. Hamiltonian Cycle (25)
  详细解决方案

PAT - 甲级 - 1122. Hamiltonian Cycle (25)

热度:96   发布时间:2023-10-09 15:46:57.0

题目描述:

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:
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

题目思路:

题目中只是说了一个环中,包含图中所有的元素,那么这样的环就是Hamiltonian环。题目中的描述给出的信息是非常有限的,当然如果你知道哈密顿回路的定义,那么你只需要稍微一看就知道题目要求什么了。言归正传,因为题目中给定的信息有限,我们需要根据给出的测试用例来推断题目的要求。根据题目给出的用例,我们可以推断这个环具备的条件(属性)。

1.包含所有元素

2.第一个元素和最后一个元素相同(即能构成环)

3.元素个数一定不小于n

但是还有一个疑问,元素是否可以重复?(除第一个和最后一个元素)。

根据题目给定的描述是无法判定的,我们可以先提交一次不判重的代码(或者判重的代码)。果然有一个测试用例的答案是错误的,因此元素是不能重复的。

题目代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int e[205][205];
int n, m, t, k, a[205], x, y,flag = 1;
int main(){scanf("%d%d",&n,&m);memset(e,0,sizeof(e));// 数据输入 for(int i = 0; i < m; i++){scanf("%d%d",&x, &y);e[x][y] = e[y][x] = 1;}scanf("%d",&t);while(t--){flag = 1;scanf("%d",&k);if(k != n+1){ // 判断元素个数 for(int i = 0; i < k; i++){scanf("%d",&a[0]);}flag = 0;}else{for(int i = 0; i < k; i++){scanf("%d", &a[i]);}if(a[0] != a[k-1]){ // 首尾元素比较 flag = 0;}else{for(int i = 0; i < k-1; i++){ // 是否通路判断 if(!e[a[i]][a[i+1]]){flag = 0;break;}}sort(a,a+n-1);for(int i = 0; i < k-1; i++){ // 判断重复元素 if(a[i] == a[i+1]){flag = 0;break;}}}}if(flag)puts("YES");else puts("NO");}	return 0;
}



  相关解决方案