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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "stdio.h"
#include "algorithm"
#include "string.h"
#include "queue"
#include "vector"
#include "set"
using namespace std;
const int maxv = 210;
const int INF = 1000000000;
int n, m, G[maxv][maxv];
bool vis[maxv] = {false};

bool isConnet(int arr[],int n){
int u = arr[0];
for (int i = 1; i < n; i++){
if(G[u][arr[i]] != 1) return false;
u = arr[i];
}
return true;
}
bool isHamilt(int arr[],int n){
if(arr[0] != arr[n - 1]) return false;
int *times = new int[n];
for(int i = 0;i < n ;i++)
times[i] = 0;
for(int i = 0;i < n ;i++)
times[arr[i]] ++;
for(int i = 1;i < n ;i++){
if(i == arr[0]){
if(times[i] != 2)
return false;
}else{
if(times[i] !=1)
return false;
}
}
return true;
}

int main(){
scanf("%d%d", &n, &m);
fill(G[0], G[0] + maxv * maxv, INF);
int u, v;
for (int i = 0; i < m; i++){
scanf("%d%d", &u, &v);
G[u][v] = G[v][u] = 1;
}
int query, k;
scanf("%d", &query);
for (int i = 0; i < query; i++){
scanf("%d", &k);
int *arr = new int[k];
for(int j = 0; j < k; j++){
scanf("%d", &arr[j]);
}
if(k == n + 1&&isHamilt(arr,k) && isConnet(arr,k)){
printf("YES\n");
}else{
printf("NO\n");
}
}

return 0;
}