码迷,mamicode.com
首页 > 其他好文 > 详细

1122 Hamiltonian Cycle (25 分)

时间:2019-08-09 13:46:46      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:insert   and   ++   ase   cycle   eve   enter   ali   back   

1122 Hamiltonian Cycle (25 分)
 

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 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 Kwhich is the number of queries, followed by K lines of queries, each in the format:

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

就多判断几下了,感觉都不涉及图的知识

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n, m, k, p;
 4 vector<int> vt;
 5 int v[500][500];
 6 int main(){
 7     cin >> n >> m;
 8     int x, y;
 9     for(int i = 0; i < m; i++){
10         cin >> x >> y;
11         v[x][y] = 1;
12         v[y][x] = 1;
13     }
14     cin >> k;
15     while(k--){
16         cin >> p;
17         vt.clear();
18         for(int i = 0; i < p; i++){
19             cin >> x;
20             vt.push_back(x);
21         }
22         set<int> s;
23         if(p == n+1){
24             if(vt[0] == vt[vt.size()-1]){
25                 bool flag = true;
26                 for(int i = 1; i < vt.size(); i++){
27                     if(v[vt[i-1]][vt[i]] == 0){
28                         flag = false;
29                         break;
30                     }
31                     s.insert(vt[i]);
32                 }
33                 if(flag && s.size() == n){
34                     cout << "YES" << endl;
35                 }else{
36                     cout <<"NO"<<endl;
37                 }
38             }else{
39                 cout << "NO" << endl;
40             }
41         }else{
42             cout << "NO" << endl;
43         }
44     }
45 
46     return 0;
47 }

 





1122 Hamiltonian Cycle (25 分)

标签:insert   and   ++   ase   cycle   eve   enter   ali   back   

原文地址:https://www.cnblogs.com/zllwxm123/p/11326501.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!