题目
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
1
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
题意
给出一个无向图的顶点,边信息。然后输入一串查询数字,问,输入的这些查询数字是否能够组成一个simple cycle。
这里simple的定义指的是:不含冗余顶点
cycle的定义就是:给出的顶点集形成了一个环
如果是simple cycle,则输出YES;如果不是simple cycle,则输出NO;
#include<iostream>
#include<set>
using namespace std;
int connected[201][201];//查询两个点是否连通用邻接矩阵更好
int N,M,K;
int main(){
cin>>N>>M;
int i,j;//下次记得定义i,j提前定义,防止产生错误
while(M--){
cin>>i>>j;
connected[i][j]=connected[j][i]=1;
}
cin>>K;
while(K--){
int n;
cin>>n;
int a[n];//路径
for(int i=0;i<n;i++){
cin>>a[i];
}
if(a[0]==a[n-1]){//是环
if(n==N+1)//边数等于点数+1,连通
{
int visited[300]={0};
for(i=1;i<n;i++){//都经过
if(visited[a[i]])break;
visited[a[i]]=1;
}
if(i==n){//正好都经过
for(i=1;i<n;i++){//通不通?
if(!connected[a[i]][a[i-1]]){//看看他跟他前面的
break;//不通
}
}
if(i==n){
cout<<"YES"<<endl;
continue;
}
}
}
}
cout<<"NO"<<endl;
}
}