1122. Hamiltonian Cycle (25)

来源:互联网 发布:linux培训ujiuye 编辑:程序博客网 时间:2024/05/16 16:15


时间限制
300 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 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
n为顶点数,m为边数。

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);//  -1for(j=0;j<num-2;j++){//  -2if(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");}}} 


0 0
原创粉丝点击