Pat 甲级 训练真题集 1122!

1122. Hamiltonian Cycle (25)

​ 时间限制

​ 300 ms

​ 内存限制

​ 65536 kB

​ 代码长度限制

​ 16000 B

​ 判题程序

​ Standard

​ 作者

​ CHEN, Yue

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

此题题意为一个简单圆包含了所有顶点,就有圆上的定点除了首尾一样,其余不能有重复,个数必须为n+1,否则必有小圆,在点与点连接时判断有无线

利用map数组存地图,

collection数组记录已访问

代码如下:

#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
#define max 201
#define query_max 100001
vector<int> vec[query_max];
int map[max][max];
int collection[max];
int main(){
	int n,edge;
	scanf("%d%d",&n,&edge);
	int v1,v2;
	for(int i=0;i<edge;++i){
		scanf("%d%d",&v1,&v2);
		map[v1][v2]=1;
		map[v2][v1]=1;
	}
	int query;	
	scanf("%d",&query);
	int size,value;
	for(int i=0;i<query;++i){
		scanf("%d",&size);
		vec[i].resize(0);
		for(int j=0;j<size;++j){
			scanf("%d",&value);
			vec[i].push_back(value);
		}
		if(vec[i].size()!=(n+1)){
		//	printf("%d %d\n",vec[i].size(),n+1);
			printf("NO\n");
		//	printf("ssss\n");
		}else{
			if(vec[i][0]!=vec[i][vec[i].size()-1]){
				printf("NO\n");
		
			}else{
				memset(collection,0,sizeof(collection));
				collection[vec[i][0]]=1;
				int q=1;
				for(;q<vec[i].size();++q){
					if(collection[vec[i][q]]==1&&q!=vec[i].size()-1){
						printf("NO\n");
						
						break;
					}
					if(map[vec[i][q]][vec[i][q-1]]!=1){
						printf("NO\n");
						
						break;
					}else{
						collection[vec[i][q]]=1;
					}
				}
				if(q==vec[i].size()){
					printf("YES\n");
				}
			}		
		}	
	}
	return 0;
}

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦