PAT (Advanced Level) Practice 1122 Hamiltonian Cycle (25分)

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

2.代码

#include<iostream>
#include<vector>
using namespace std;
int edges[201][201];
int main()
{
	int n, m,a,b,k,amount;
	scanf("%d %d", &n, &m);
	for (int i = 1; i <=m; i++)
	{
		scanf("%d %d", &a, &b);
		edges[a][b] = edges[b][a] = 1;
	}
	scanf("%d", &k);
	
	for (int i = 1; i <=k; i++)
	{
		bool ok = true;
		scanf("%d", &amount);
		vector<int>in(amount);
		vector<int>mark(n+1);
		for (int i = 0; i < amount; i++)
			scanf("%d", &in[i]);
		if (amount < n) { printf("NO\n");  continue; }
		if ((amount == 0 || amount == 1) && amount == n) { printf("YES\n"); continue; }
		int j;
		for ( j = 0; j < amount - 1; j++)
		{
			if (mark[in[j]] == 1) { ok = false; break; }
			if (edges[in[j]][in[j + 1]] == 0) { ok = false; break; }
			mark[in[j]] = 1;
		}
		if (in[j]!=in[0])ok = false;
		if (ok)printf("YES\n");
		else printf("NO\n");
	}
}

 

posted @ 2020-04-01 11:45  Jason66661010  阅读(113)  评论(0编辑  收藏  举报