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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <algorithm> 3 #include <iostream> 4 #include <map> 5 #include <vector> 6 #include <set> 7 using namespace std; 8 int n,m,k; 9 int dis[201][201]; 10 int path[1000],vis[201]; 11 int main(){ 12 scanf("%d %d",&n,&m); 13 for(int i=0;i<m;i++){ 14 int c1,c2; 15 scanf("%d %d",&c1,&c2); 16 dis[c1][c2]=1; 17 dis[c2][c1]=1; 18 } 19 scanf("%d",&k); 20 int min=99999999,mini=0; 21 for(int i=1;i<=k;i++){ 22 int flag=0; 23 int total=0; 24 int nn; 25 fill(vis,vis+201,0); 26 scanf("%d",&nn); 27 for(int j=0;j<nn;j++){ 28 scanf("%d",&path[j]); 29 vis[path[j]]++; 30 } 31 for(int j=1;j<=n;j++){ 32 if(vis[j]==0) flag=1; 33 } 34 if(nn!=n+1 || path[0]!=path[nn-1]) flag=1; 35 for(int j=1;j<nn;j++){ 36 if(dis[path[j]][path[j-1]]==0){ 37 flag=1; 38 break; 39 } 40 } 41 if(flag==1) printf("NO "); 42 else{ 43 printf("YES "); 44 } 45 } 46 }
注意点:挺简单的一道题,就按题目意思实现一下,判断给的路径是否是一个环,这个环有没有包含所有节点,并且是联通的,点除了起点都只经过一次。和1150 Travelling Salesman Problem (25 分)差不多,比他更简单一些