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

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 (2Vertex1 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

 22分:

又臭又长的代码:

#include 
#include 
using namespace std;

int n, m, k; //顶点和边数
int visit[201] = {0};
int cnt = 0;
int g[201][201] = {0};

void dfs(int node, vector a)
{
	visit[a[node]]++;
	for (int i = node+1; i < a.size(); i++)
	{
		if (g[a[node]][a[i]] == 1)
		{
			dfs(i,a);
			break;
		}
	}
}
int main()
{
	scanf("%d %d", &n, &m);
	for(int i = 0; i < m; i++)
	{
		int a,b;
		scanf("%d %d", &a, &b);
		g[a][b] = g[b][a] = 1;
	}

	scanf("%d", &k);
	for (int i = 0; i < k; i++)
	{
		int num;
		scanf("%d", &num);

		vector ver(num,0); // 查询路径序列

		for (int j = 0; j < num; j++)
		{
			scanf("%d", &ver[j]);
		}
		
		if (ver[0] == ver[num-1] && num >= n) //回到起点
		{
			cnt = n-1;
			fill(visit, visit+201, 0);
			dfs(0, ver);
			for (int k = 1; k < ver.size()-1; k++)
			{
				if (visit[ver[k]] > 1 || visit[ver[k]] == 0)
				{
					cnt--;
				}
			}
			if (cnt != n-1)
			{
				printf("NO\n");
			}else
			{
				printf("YES\n");
			}
			
		}else
		{
			cnt = 0;
			printf("NO\n");
		}
		
	}
	return 0;
}

参考代码(柳神):

学习点:

1. 判断节点是否多走、少走、或走成环
2.  判断这条路能不能走通,不需要dfs,直接判断即可..

#include 
#include 
#include 
using namespace std;

int main()
{
	int n, m, num, k,g[201][201] = {0};
	scanf("%d %d", &n, &m);
	for (int i = 0; i < m; i++)
	{
		int a,b;
		scanf("%d%d", &a, &b);
		g[a][b] = g[b][a] = 1;
	}
	scanf("%d", &num);
	while(num--)
	{
		scanf("%d", &k);
		vector v(k);
		set s;
		for (int i = 0; i < k; i++)
		{
			scanf("%d", &v[i]);
			s.insert(v[i]);
		}
		int flag1 = 1, flag2 = 1;
		if (s.size() != n || v[0] != v[k-1] || k - 1 != n) flag1= 0;
		for (int i = 0; i < k - 1; i++)
		{
			if(g[v[i]][v[i+1]] == 0) flag2 = 0;
		}

		if (flag1 && flag2)
		{
			printf("YES\n");
		}else
		{
			printf("NO\n");
		}
	}

}

 

你可能感兴趣的:(反复看,PAT甲级)