PAT_A1122#Hamiltonian Cycle
Source:
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 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
YESif the path does form a Hamiltonian cycle, orNOif 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-20 16:30:23 3 Problem: PAT_A1122#Hamiltonian Cycle 4 AC: 12:29 5 6 题目大意: 7 H圈定义:简单圈且包含全部顶点; 8 判断所给圈是否为H圈 9 */ 10 #include<cstdio> 11 #include<set> 12 #include<algorithm> 13 using namespace std; 14 const int M=220; 15 int grap[M][M],path[M]; 16 17 int main() 18 { 19 #ifdef ONLINE_JUDGE 20 #else 21 freopen("Test.txt", "r", stdin); 22 #endif // ONLINE_JUDGE 23 24 fill(grap[0],grap[0]+M*M,0); 25 int n,m,k,v1,v2; 26 scanf("%d%d", &n,&m); 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 while(m--) 35 { 36 set<int> ver; 37 scanf("%d", &k); 38 for(int i=0; i<k; i++){ 39 scanf("%d", &path[i]); 40 ver.insert(path[i]); 41 } 42 int reach=1; 43 for(int i=0; i<k-1; i++){ 44 if(grap[path[i]][path[i+1]]==0){ 45 reach=0;break; 46 } 47 } 48 if(reach==0 || path[0]!=path[k-1] || ver.size()!=n || k!=n+1) 49 printf("NO\n"); 50 else 51 printf("YES\n"); 52 } 53 54 return 0; 55 }
浙公网安备 33010602011771号