A1122. Hamiltonian Cycle

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 #include<cstdio>
 2 #include<iostream>
 3 #include<vector>
 4 using namespace std;
 5 const int INF = 100000000;
 6 int G[201][201], visit[201] = {0,0};
 7 int main(){
 8     int N, M;
 9     fill(G[0], G[0] + 201*201, INF);
10     scanf("%d%d", &N, &M);
11     for(int i = 0; i < M; i++){
12         int v1, v2;
13         scanf("%d%d", &v1, &v2);
14         G[v1][v2] = G[v2][v1] = 1;
15     }
16     int K;
17     scanf("%d", &K);
18     for(int i = 0; i < K; i++){
19         int n, s, vi, vj, tag = 1;
20         fill(visit, visit + 201, 0);
21         scanf("%d%d", &n, &s);
22         if(n != N + 1)
23             tag = 0;
24         visit[s] = 1;
25         vi = s;
26         for(int j = 1; j < n; j++){
27             scanf("%d", &vj);
28             if(G[vi][vj] == INF){
29                 tag = 0;
30             }
31             visit[vj]++;
32             vi = vj;
33         }
34         if(vj != s)
35             tag = 0;
36         for(int i = 1; i <= N; i++){
37             if(i != s && visit[i] != 1 || i == s && visit[i] != 2)
38                 tag = 0;
39         }
40         if(tag == 0)
41             printf("NO
");
42         else printf("YES
");
43     }
44     return 0;
45 
46 }
View Code

总结:

1、哈密顿回路:图中所有顶点必须都出现,除了首尾是重复出现外,其它节点仅出现一次。   顶点组成的序列必须是联通的。   

2、注意,边读入边做处理时,不要使用break,造成读入数据错乱。

原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/8580406.html