博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT甲级——A1122 Hamiltonian Cycle【25】
阅读量:4542 次
发布时间:2019-06-08

本文共 2709 字,大约阅读时间需要 9 分钟。

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:

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 106 23 41 52 53 14 11 66 31 24 567 5 1 4 3 6 2 56 5 1 4 3 6 29 6 2 1 6 3 4 5 2 64 1 2 5 17 6 1 3 4 5 2 67 6 1 2 5 4 3 1

Sample Output:

YESNONONOYESNO 第一,遍历点K一定等于N+1,因为既要遍历且一次所有顶点,而且回到起点 第二,遍历的最后一个点一定是起点 使用visit记录顶点是否遍历过了,graph记录路径是否能行
1 #include 
2 #include
3 using namespace std; 4 int main() 5 { 6 int n, m, k, a, b, start, graph[205][205]; 7 bool visit[205];//记录每个顶点遍历一次 8 fill(graph[0], graph[0] + 25 * 205, -1); 9 cin >> n >> m;10 while (m--)11 {12 cin >> a >> b;13 graph[a][b] = graph[b][a] = 1;14 }15 cin >> m;16 while (m--)17 {18 cin >> k;19 bool flag = true;20 fill(visit, visit + 205, false);21 for (int i = 0; i < k; ++i)22 {23 cin >> b;24 if (flag == false || k != n + 1)//遍历所有的顶点并回到起点,则一定走过n+1个点25 {26 flag = false;27 continue;28 }29 if (i == 0)30 start = b;//记录起点31 else if (graph[a][b] != 1)//此路不通32 flag = false;33 else if (i == k - 1 && b != start)//最后一个点不是起点34 flag = false;35 else if (i != k - 1 && visit[b] != false)//除了最后一次重复遍历起点,出现了其他点重复遍历,36 flag = false;37 else38 visit[b] = true;//遍历过39 a = b;//记录前一个点40 }41 if (flag)42 {43 for (int i = 1; i <= n && flag == true; ++i)44 if (visit[i] == false)//存在没有遍历的顶点45 flag = false;46 if (flag)47 cout << "YES" << endl;48 }49 if (flag == false)50 cout << "NO" << endl;51 }52 return 0; 53 }

 

 

转载于:https://www.cnblogs.com/zzw1024/p/11470328.html

你可能感兴趣的文章
2013年11月15日
查看>>
Android5.0Demo
查看>>
c++ UDP套接字客服端代码示范
查看>>
python中的关键字---1(基础数据类)
查看>>
《windows程序设计》文本输出(03)
查看>>
虚拟机、容器与Docker
查看>>
波兰表达式
查看>>
总结一下几个for循环常见用法和区别
查看>>
LNMP安装目录及配置文件位置
查看>>
out 传值
查看>>
8. 负载均衡算法
查看>>
python把函数作为参数的函数
查看>>
《C++ Primer》之指向函数的指针
查看>>
Java自学笔记(第五天)面向对象--char[]和String--封装--构造函数--this
查看>>
8.6 每日课后作业之递归调用番外篇(迭代器)
查看>>
CodeForces 55D Beautiful numbers(数位dp+数学)
查看>>
PAT甲级——A1048 Find Coins
查看>>
PAT甲级——A1049 Counting Ones
查看>>
PAT甲级——A1050 String Subtraction
查看>>
PAT甲级——A1021 Deepest Root
查看>>