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 ... 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
- 除首尾外,不会再有相同的顶点。
- 序列中相邻的两个顶点要求有边相连。
满足这些条件可以判断这是一条哈密顿回路。
代码:
#include<stdio.h>
#include<vector>
#include<string.h>
using namespace std;
int Map[210][210];
vector<int> v;
int n;
int num[210];
int judge()
{
int i,j;
if(v[0]!=v[v.size()-1])
{
return 0;
}
else
{
for(i=0;i<v.size()-1;i++)
{
if(Map[v[i]][v[i+1]]!=1)
{
break;
}
}
if(i<v.size()-1)
{
return 0;
}
for(i=1;i<=n;i++)
{
if(num[i]>2)
break;
else if(num[i]==2&&i!=v[0])
break;
else if(num[i]<1)
break;
}
if(i<=n)
{
return 0;
}
}
return 1;
}
int main()
{
int i,j,m,k,t,x,y,node;
scanf("%d %d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d %d",&x,&y);
Map[x][y]=Map[y][x]=1;
}
scanf("%d",&k);
for(i=0;i<k;i++)
{
memset(num,0,sizeof(num));
scanf("%d",&t);
v.clear();
for(j=0;j<t;j++)
{
scanf("%d",&node);
v.push_back(node);
num[node]++;
}
if(t!=n+1)
{
printf("NO\n");
}
else
{
if(judge())
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}