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<N≤200), the number of vertices, and M, the number of edges in an undirected graph. Then Mlines 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 Klines 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
题意:
给出一个图,并给出每次询问,判断每次询问的路径是否为哈密尔顿回路
思路:
先建图,然后用bool的vis数组判断是否访问过了,终点另外判断(稍微模拟的有一些麻烦)
#include<iostream>
#include<set>
#include<cstring>
using namespace std;
const int maxn=250;
const int INF =1000000;
int g[maxn][maxn]={INF};
int road[maxn];
bool vis[maxn]={false};
set<int>s;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
g[a][b]=1;
g[b][a]=1;
}
int k;
scanf("%d",&k);
while(k--)
{
int num;
memset(vis,false,sizeof(vis));
s.clear();
cin>>num;
int st;
scanf("%d",&st);
int temp=st;//记录起点
vis[st]=true;
int flag=0;
s.insert(st);
for(int i=1;i<num-1;i++)
{
int x;
scanf("%d",&x);
//起点到x有路且x没有访问过
if(g[st][x]!=1||vis[x]==true)
{
flag=1;
continue;
}
s.insert(x);
st=x;
}
//cout<<s.size()<<endl;
int end;
scanf("%d",&end);
if(g[st][end]!=1||end!=temp)
flag=1;
if(s.size()!=n)
flag=1;
if(flag==1)
printf("NO\n");
else
printf("YES\n");
}
}