1122. Hamiltonian Cycle (25)(哈密顿)

来源:互联网 发布:windows rt连接口 编辑:程序博客网 时间:2024/06/06 13:10
  1. 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 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。路径第一个节点应该与最后一个节点相同
2。路径节点没有重复
3。每一条路都是存在的

#include<iostream>#include<set>using namespace std;int rea[205][205];int cyc[205];set<int > s;int n,m,p,a,b,temp,k;int pd(){    for (int i=2;i<=p;i++)    {        if (rea[cyc[i-1]][cyc[i]]!=1)        {            return 0;        }    }    return 1;}int main(){    cin>>n>>m;    for (int i=0;i<m;i++)    {        cin>>a>>b;        rea[a][b]=rea[b][a]=1;    }    cin>>k;    for (int i=1;i<=k;i++)    {        s.clear();        cin>>p;        for (int t=1;t<=p;t++)        {            cin>>temp;            cyc[t]=temp;            s.insert(temp);        }        if (cyc[1]==cyc[p]&&s.size()==n&&n==p-1&&pd()==1)//关键部分        {            cout<<"YES"<<endl;        }        else        {            cout<<"NO"<<endl;        }    }    return 0;}
原创粉丝点击