1122 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
题目大意:给定一图,判断给定路径是否为汉密尔顿路径。
分析:设置flag1,判断结点是否少走、重走或者形成回路。
设置flag2,判断给定路径是否连通。
参考代码:
#include<iostream>
#include<vector>
#include<cstring>
#include<set>
#define N 205
using namespace std;
int graph[N][N];
int main() {
int n, e, ver1, ver2, k, m;
scanf("%d%d", &n, &e);
memset(graph, 0, sizeof(int)*N);
for (int i = 1; i <= e; i++) {
scanf("%d%d", &ver1, &ver2);
graph[ver1][ver2] = 1;
graph[ver2][ver1] = 1;
}
scanf("%d", &k);
for (int i = 1; i <= k; i++) {
scanf("%d", &m);
int flag1 = 1, flag2 = 1;
vector<int>v(m);
set<int>s;
for (int j = 0; j <m; j++) {
scanf("%d", &v[j]);
s.insert(v[j]);
}
if (s.size() != n || n!= m - 1 || v[0] != v[m - 1]) flag1 = 0;
for (int j = 0; j < m - 1; j++) {
if (graph[v[j]][v[j + 1]] != 1) {
flag2 = 0; break;
}
}
if (flag1&&flag2)printf("YES\n"); else printf("NO\n");
}
return 0;
}
欢迎评论!!!
本文介绍了一种算法,用于判断给定路径是否构成图论中的汉密尔顿圈。通过遍历输入路径并检查其是否包含所有顶点且形成闭合环路,同时验证路径上各顶点间是否直接相连。
323

被折叠的 条评论
为什么被折叠?



