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,
where n is the number of vertices in the list, and V
'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、每个点只能访问一次
简单的图问题,使用临界矩阵存储图信息,vis 数组判断访问次数,具体代码见下图:
#include<iostream>
#include<bits/stdc++.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<deque>
#include<unordered_set>
#include<unordered_map>
#include<cctype>
#include<algorithm>
#include<stack>
using namespace std;
const int N = 201;
int G[N][N];
int n, m;
int main() {
cin >> n >> m;
while (m--) {
int x, y;
cin >> x >> y;
G[x][y] = 1;
G[y][x] = 1;
}
int k;
cin >> k;
while (k--) {
int kk;
cin >> kk;
bool vis[n + 1] = {0};
int u, uu;
cin >> u;
uu = u;
bool flagA = true, flagB = true;
for (int i = 1; i < kk; i++) {
int v;
cin >> v;
if (!G[u][v] || vis[v]) {
flagA = false;
continue;
}
vis[v] = true;
u = v;
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
flagB = false;
break;
}
}
if (u != uu) {
flagB = false;
}
if (flagA && flagB) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}