PAT1122: Hamiltonian Cycle

1122. Hamiltonian Cycle (25)

时间限制
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 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.输入的节点个数必须等于 总结点数 + 1
2.不能有重复出现的节点(只能走一次,起点除外)
3.起点终点必须相同。
4.两个节点之间必须直接相通(即被一条直线直接相连)

代码
#include<iostream>
#include<vector>
#include<set>
using namespace std;
vector<vector<int>> graph(201,vector<int>(201,-1));
int main()
{
    int N,M;
    while(cin >> N >> M )
    {
        for(int i = 1;i <= M;i++)
        {
            int a,b;
            cin >> a >> b;
            graph[a][b] = graph[b][a] = 1;
        }
        int K;
        cin >> K;
        for(int i = 0;i < K;i++)
        {
            int n;
            set<int> visits;
            cin >> n;
            vector<int> nodes(n + 1);
            for(int j = 1;j <= n;j++)
            {
               cin >> nodes[j];
               visits.insert(nodes[j]);

            }
            if(n != N + 1 || nodes[1] != nodes[n] || visits.size() != N)
            {
                cout << "NO" << endl;
                continue;
            }
            bool isha = true;
            for(int j = 2;j <= n;j++)
            {
                if(graph[nodes[j]][nodes[j - 1]] != 1)
                {
                    isha = false;
                    break;
                }
            }
            if(isha)
                cout << "YES" << endl;
            else
                cout << "NO" << endl;
        }
    }
}

  

posted @ 2017-11-28 16:16  0kk470  阅读(190)  评论(0编辑  收藏  举报