PAT A1122 Hamiltonian Cycle (25 分)——图遍历

时间:2023-03-09 03:18:36
PAT A1122 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 (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
 #include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
int n,m,k;
int dis[][];
int path[],vis[];
int main(){
scanf("%d %d",&n,&m);
for(int i=;i<m;i++){
int c1,c2;
scanf("%d %d",&c1,&c2);
dis[c1][c2]=;
dis[c2][c1]=;
}
scanf("%d",&k);
int min=,mini=;
for(int i=;i<=k;i++){
int flag=;
int total=;
int nn;
fill(vis,vis+,);
scanf("%d",&nn);
for(int j=;j<nn;j++){
scanf("%d",&path[j]);
vis[path[j]]++;
}
for(int j=;j<=n;j++){
if(vis[j]==) flag=;
}
if(nn!=n+ || path[]!=path[nn-]) flag=;
for(int j=;j<nn;j++){
if(dis[path[j]][path[j-]]==){
flag=;
break;
}
}
if(flag==) printf("NO\n");
else{
printf("YES\n");
}
}
}

注意点:挺简单的一道题,就按题目意思实现一下,判断给的路径是否是一个环,这个环有没有包含所有节点,并且是联通的,点除了起点都只经过一次。和1150 Travelling Salesman Problem (25 分)差不多,比他更简单一些