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 (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个结点以及m条边,以及k个序列,每个序列都给出一个数num,以及num个结点序号,请问是否为汉密尔顿环,即是否为连通分量的一条路径。
思路:
用邻接矩阵存储图,当遍历到e[a][b] == 0 时置flag = false,并且break出来,否则遍历完序列,如果flag == false那么输出NO就可以了,否则呢还要验证是否全部遍历过,用vis[id]来记录,且vis[start] == 2, 如果都是了才能输出YES。
注意:如果num != n + 1时一定不是正确序列,这个可以增加判断,提高效率,此题中如果不进行判断的话,也能通过。
参考代码:
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
vector<int> path, vis;
int e[201][201];
int n, m, k, num;
int main(){
scanf("%d%d", &n, &m);
vis.resize(n + 1);
for(int i = 0; i < m; ++i){
int a, b;
scanf("%d%d", &a, &b);
e[a][b] = e[b][a] = 1;
}
scanf("%d", &k);
for(int i = 0; i < k; ++i){
scanf("%d", &num);
path.resize(num);
for(int j = 0; j < num; ++j) scanf("%d", &path[j]);
if(num != n + 1){
printf("NO\n");
continue;
}
bool flag = true;
int cnt = 0;
for(int j = 0; j < num - 1; ++j){
int a = path[j], b= path[j + 1];
if(e[a][b] == 0){
flag = false;
break;
}
vis[a]++; vis[b]++; cnt++;
}
if(cnt != n || vis[path[0]] != 2) flag = false;
if(!flag) printf("NO\n");
else printf("YES\n");
fill(vis.begin(), vis.end(), 0);
}
return 0;
}