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 1Sample Output:
YES NO NO NO YES NO
m条边。
k为查询次数。
每次查询的顶点数。顶点...
汉密尔顿回路。
1.除起点外,经过所有顶点一次。sort排序检查。
2.起点和终点相同。
3.顶点数为n+1.
#include<stdio.h>
#include<algorithm>
using namespace std;
int map[201][201];
int main(){
int n,m,i,j,k,c1,c2;
scanf("%d%d",&n,&m);
for(i=0;i<m;i++){
scanf("%d %d",&c1,&c2);
map[c1][c2]=map[c2][c1]=1;
}
scanf("%d",&k);
int num;
for(i=0;i<k;i++){
scanf("%d",&num);
int a[num];
int b[num];
for(j=0;j<num;j++){
scanf("%d",&a[j]);
b[j]=a[j];
}
if(num!=n+1||a[0]!=a[num-1]){//条件2,3
printf("NO\n");
continue;
}
int flag=1;
sort(a,a+n);
for(j=0;j<n-1;j++){
if(a[j]==a[j+1]){//条件1
flag=0;
break;
}
}
if(flag==0){
printf("NO\n");
continue;
}
else{
for(j=0;j<num-1;j++){
if(map[b[j]][b[j+1]]==0){
flag=0;break;
}
}
if(flag==0){
printf("NO\n");
continue;
}
else{
printf("YES\n");
}
}
}
}
#include<stdio.h>
#include<algorithm>
using namespace std;
int adj[210][210]={0};
int check(int n){
int j,num;
scanf("%d",&num);
int a[num],b[num];
for(j=0;j<num;j++){
scanf("%d",&a[j]);
b[j]=a[j];
}
if(num!=n+1){
return 0;
}
else if(a[0]!=a[num-1]){
return 0;
}
else{
sort(b,b+num-1);// -1
for(j=0;j<num-2;j++){// -2
if(b[j]==b[j+1]){
return 0;
}
}
for(j=0;j<num-1;j++){
if(adj[a[j]][a[j+1]]==0){
return 0;
}
}
}
return 1;
}
int main(){
int n,m,k,i,c1,c2,j;
scanf("%d %d",&n,&m);
for(i=0;i<m;i++){
scanf("%d %d",&c1,&c2);
adj[c1][c2]=adj[c2][c1]=1;
}
scanf("%d",&k);
for(i=0;i<k;i++){
int flag=check(n);
if(flag){
printf("YES\n");
}
else{
printf("NO\n");
}
}
}