PAT (Advanced Level) Practice 1122 Hamiltonian Cycle(25 分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Puppettt/article/details/82180370

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 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 Kwhich is the number of queries, followed by K lines of queries, each in the format:

n V​1​​ V​2​​ ... V​n​​

where n is the number of vertices in the list, and V​i​​'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

题意 :哈密顿圈。包含所有点的简单环。

思路:判断首尾是否相同。判断是否所有点都当且仅出现过一次。判断是否连通。

代码:

#include <bits/stdc++.h>
using namespace std;
vector<int>lin[220];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    int a,b,vis[220]={0};

    for(int i=0;i<m;i++)
    {
        scanf("%d%d",&a,&b);
        lin[a].push_back(b);
        lin[b].push_back(a);
    }
    int q;scanf("%d",&q);

    while(q--)
    {
        memset(vis,0,sizeof(vis));
        int k;scanf("%d",&k);
        vector<int>v;
        for(int i=0;i<k;i++)
        {
            scanf("%d",&a);
            v.push_back(a);
        }
        if(k!=(n+1))printf("NO\n");
        else{
            if(v[0]!=v[k-1])printf("NO\n");
            else{
                int flag=1;
                for(int i=1;i<k;i++)
                {
                    vis[v[i]]++;
                    if(vis[v[i]]>1)
                    {
                        flag=0;
                        break;
                    }
                    a=v[i-1];
                    int ok=0;
                    for(int j=0;j<lin[a].size();j++)
                    {
                        if(lin[a][j]==v[i]){
                            ok=1;
                            break;
                        }
                    }

                    if(ok==1)continue;
                    else {
                        flag=0;
                        break;
                    }
                }
                if(flag)printf("YES\n");
                else printf("NO\n");
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Puppettt/article/details/82180370
今日推荐