1122 Hamiltonian Cycle
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 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
题意:
给出一个图,判断所给的节点是不是哈密尔顿路径。
思路:
1. 首先判断所给的路径是不是连通。
2. 判断是不是给出了图中的全部结点。
3. 判断路径的起点和终点是不是相同。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 int n, m, k; 7 cin >> n >> m; 8 vector<vector<int> > grap(n + 1, vector<int>(n + 1, 0)); 9 int v1, v2; 10 for (int i = 0; i < m; ++i) { 11 cin >> v1 >> v2; 12 grap[v1][v2] = 1; 13 grap[v2][v1] = 1; 14 } 15 cin >> k; 16 int num; 17 set<int> s; 18 bool isHamiltonianCycle; 19 for (int i = 0; i < k; ++i) { 20 cin >> num; 21 vector<int> v(num); 22 s.clear(); 23 isHamiltonianCycle = true; 24 for (int j = 0; j < num; ++j) { 25 cin >> v[j]; 26 s.insert(v[j]); 27 } 28 if (num != n + 1 || s.size() != n) 29 isHamiltonianCycle = false; 30 else { 31 for (int j = 1; j < num; ++j) { 32 if (grap[v[j]][v[j - 1]] == 0) { 33 isHamiltonianCycle = false; 34 break; 35 } 36 } 37 } 38 if (v[0] != v[num - 1]) isHamiltonianCycle = false; 39 if (isHamiltonianCycle) 40 cout << "YES" << endl; 41 else 42 cout << "NO" << endl; 43 } 44 return 0; 45 }
相关文章
- 出现net.sf.json.JSONException: There is a cycle in the hierarchy异常的解决办法
- leetcode 之Linked List Cycle(24)
- 【异常】The dependencies of some of the beans in the application context form a cycle
- go环境import cycle not allowed问题处理
- [Cycle.js] Hyperscript as our alternative to template languages
- [Cycle.js] Main function and effects functions
- [Cycle.js] Hyperscript as our alternative to template languages
- 6. Activity life cycle
- [LeetCode] Linked List Cycle II
- [LeetCode] Linked List Cycle
- atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy
- 【ICM Technex 2018 and Codeforces Round #463 (Div. 1 + Div. 2, combined) C】 Permutation Cycle
- 【34.57%】【codeforces 557D】Vitaly and Cycle
- 【Codeforces Beta Round #88 C】Cycle
- A cycle was detected in the build path of project
- [LeetCode] Linked List Cycle II