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< N <= 200), 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 ... Vnwhere 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 1Sample Output:YESNONONOYESNO
題意就是輸入一個圖 然后在輸入多行數據 每一行表示一個軌跡 需要分析這個軌跡是否構成哈密頓回路
哈密頓回路就是一條能夠串聯起圖中所有點的回路 如何判斷呢 一開始想復雜了 以為這個行序列里有多條起點和終點 需要把每一段起點終點相同的點有可能構成回路的線段都存到向量里 最后交了一發發現其實并沒有這么復雜 只需判斷這個行序列是不是第一個數等于最后一個數 并且這之間遍歷了所有的點 那么就符合YES條件 否則輸出NO
另外 一定要判斷這條軌跡中彼此連邊是否存在 不然還讓你輸入那么多邊干嘛?
AC code:
#include<set>#include<map>#include<vector>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;struct node{ int s,e; };int a[210][210];int tre[210];int last[210];int main(){ vector<node>v; int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=m;i++) { int s,e; scanf("%d%d",&s,&e); a[s][e]=1; a[e][s]=1; } int k; scanf("%d",&k); while(k--) { int t; scanf("%d",&t); for(int i=1;i<=t;i++)scanf("%d",&tre[i]); bool ver[210]={0}; int check=n; bool flag=0; for(int i=1;i<=t;i++) { if(i>1&&a[tre[i-1]][tre[i]]!=1)break; if(!ver[tre[i]]) { check--; ver[tre[i]]=1; } else if(ver[tre[i]]&&check)break; else if(check==0&&ver[tre[i]]&&tre[1]==tre[t]&&i==t) { flag=1; break; } } if(flag)printf("YES/n"); else printf("NO/n"); } return 0;}