欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Solution of 1122. Hamiltonian Cycle (25)

程序员文章站 2022-03-08 16:17:34
...

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 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


结题思路 :
题意要求在已知的无向图上,判断一个哈密尔顿回路是否成立。
即:无向图中的每个节点都只能经过一次,这也就意味着每条边最多只能经过一次。

程序步骤:
第一步、用一位数组保存无向图。
第二步、判断连续的走向对应的边是存在的,对应的节点是未访问的。


具体程序(AC)如下:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  bool map[40205];
  memset(map, sizeof(map), 0);
  int v, e;
  cin >> v >> e;
  int start, end;
  for(int i = 0; i < e; ++i)
  {
      cin>> start >> end;
      map[start * v + end] = map[end * v + start] = 1;
  }
  int n, jump, pre, cur;
  int i;
  int path[205];
  int node[205];
  cin>> n;
  while(n--)
  {
      memset(node, 0, sizeof(node));
      cin >> jump;
      for(i = 0; i< jump; ++i)
          cin >> path[i];
      if(jump != v + 1)
      {
          cout<<"NO"<<endl;
          continue;
      }
      if(path[0] != path[jump - 1])
      {
          cout<<"NO"<<endl;
          continue;
      }
      pre = path[0];
      for(i = 1; i < jump; ++i)
      {
          cur = path[i];
          if(map[cur*v+pre]||map[pre*v+cur])
          {
            if(node[cur])
                break;
            node[cur] = 1;
            pre = cur;  
          }
          else
              break;
      }
      if(i >= jump)
          cout<<"YES"<<endl;
      else
          cout<<"NO"<<endl;
  }
  return 0;
}