其他分享
首页 > 其他分享> > PAT_A1122#Hamiltonian Cycle

PAT_A1122#Hamiltonian Cycle

作者:互联网

Source:

PAT A1122 Hamiltonian Cycle (25 分)

Description:

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), the number of vertices, and M, the number of edges in an undirected graph. Then Mlines 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 Klines 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

Keys:

Code:

 1 /*
 2 Data: 2019-06-03 21:33:04
 3 Problem: PAT_A1122#Hamiltonian Cycle
 4 AC: 32:44
 5 
 6 题目大意:
 7 H圈定义:简单圈且包含全部顶点;
 8 判断所给圈是否为H圈
 9 */
10 
11 #include<cstdio>
12 #include<algorithm>
13 using namespace std;
14 const int M=220;
15 int grap[M][M],vis[M],hc[M];
16 
17 int main()
18 {
19 #ifdef    ONLINE_JUDGE
20 #else
21     freopen("Test.txt", "r", stdin);
22 #endif
23 
24     int n,m,k,v1,v2;
25     scanf("%d%d", &n,&m);
26     fill(grap[0],grap[0]+M*M,0);
27     for(int i=0; i<m; i++)
28     {
29         scanf("%d%d", &v1,&v2);
30         grap[v1][v2]=1;
31         grap[v2][v1]=1;
32     }
33     scanf("%d", &m);
34     for(int i=0; i<m; i++)
35     {
36         scanf("%d", &k);
37         fill(vis,vis+M,0);
38         for(int j=0; j<k; j++){
39             scanf("%d", &hc[j]);
40             if(j==0)   v1=hc[j];
41             if(j==k-1) v2=hc[j];
42             if(j!=0)   vis[hc[j]]++;
43             if(vis[hc[j]]==2)
44                 vis[0]=1;
45         }
46         if(k==n+1 && v1==v2 && vis[0]==0)
47         {
48             for(int j=1; j<k; j++)
49             {
50                 v2=hc[j];
51                 if(grap[v1][v2]==0){
52                     vis[0]=1;
53                     break;
54                 }
55                 v1=v2;
56             }
57             if(vis[0]==0){
58                 printf("YES\n");
59                 continue;
60             }
61         }
62         printf("NO\n");
63     }
64 
65     return 0;
66 }

 

标签:A1122,PAT,Hamiltonian,int,NO,number,each,Cycle,cycle
来源: https://www.cnblogs.com/blue-lin/p/10970562.html