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 V
1
V
2
… V
n
where n is the number of vertices in the list, and V
i
'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
哈密顿圈,用邻接表来存。分别用两个flag来判断这是否是个哈密顿圈
将每次问的点存在一个vector里面,也插入set中,这样可以用set去重,因为首尾是相同的,去完重后判断set大小是否和n相同且输入的点-1是否和n相同,且首尾是否相同,如果有一点不满足,就使flag1位false
for遍历每两个邻接点,如果两个邻接点没有通路,flag2设为false
两个flag都为true就输出no
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
const int maxn = 210;
const int INF = 1000000000;
int G[maxn][maxn];
int main(){
fill(G[0] , G[0] + maxn * maxn, INF);
int n,m;
cin>>n>>m;
int u,v;
for(int i = 0; i < m; i++){
cin>>u>>v;
G[u][v] = G[v][u] = 1;
}
int k, q, d;
vector<int> vv;
cin>>k;
for(int i = 0; i < k; i++){
cin>>q;
bool flag1 = true, flag2 = true;
set<int> s;
vv.clear();
for(int j = 0; j < q; j++){
cin>>d;
vv.push_back(d);
s.insert(d);
}
if(s.size() != n||q-1 != n || vv[0] != vv[q-1]) flag1 = false;
for(int j = 0; j < q - 1; j++){
if(G[vv[j]][vv[j+1]] == INF) flag2 = false;
}
if(flag1 && flag2) cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}
用set去重,但是set会自动排序,这条路就和原来不一样了,所以还是最后得靠vector。
//判断相邻两个点之间是否连通;判断点集的个数和n是否相等;加入到set中,看看无重复点的个数是否和n相等
#include<iostream>
#include<set>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = 1000000000;
int G[maxn][maxn];
int main(){
fill(G[0],G[0] + maxn * maxn,INF);
int n,m;
cin>>n>>m;
int u,v;
for(int i = 0; i < m; i++){
cin>>u>>v;
G[u][v] = 1;
G[v][u] = 1;
}
int q,k,dian;
cin>>q;
for(int i = 0; i < q; i++){
cin>>k;
set<int> s;
vector<int> v;
for(int j = 0; j < k; j++){
cin>>dian;
s.insert(dian);
v.push_back(dian);
}
bool flag = true;
for(int j = 1; j < k; j++){
if(G[v[j]][v[j-1]] != 1) flag = false;
}
if(s.size() != n || v[0] != v[k-1] || k-1 != n) flag = false;
if(flag) cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}