当前位置: 代码迷 >> 综合 >> 汉密尔顿回路
  详细解决方案

汉密尔顿回路

热度:73   发布时间:2024-02-24 19:38:41.0

著名的“汉密尔顿(Hamilton)回路问题”是要找一个能遍历图中所有顶点的简单回路(即每个顶点只访问 1 次)。本题就要求你判断任一给定的回路是否汉密尔顿回路。

输入格式:

首先第一行给出两个正整数:无向图中顶点数 N(2<N≤200)和边数 M。随后 M 行,每行给出一条边的两个端点,格式为“顶点1 顶点2”,其中顶点从 1 到N 编号。再下一行给出一个正整数 K,是待检验的回路的条数。随后 K 行,每行给出一条待检回路,格式为:

n V?1?? V?2?? ? V?n??

其中 n 是回路中的顶点数,V?i?? 是路径上的顶点编号。

输出格式:

对每条待检回路,如果是汉密尔顿回路,就在一行中输出"YES",否则输出"NO"。

输入样例:

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

输出样例:

YES
NO
NO
NO
YES
NO
#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>#define CLR(a) memset(a, 0, sizeof(a))
#define pb push_backusing namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;const double PI = 3.14159265358979323846264338327;
const double E = exp(1);
const double eps = 1e-30;const int INF = 0x3f3f3f3f;
const int maxn = 2e2 + 5;
const int MOD = 1e9 + 7;int Map[maxn][maxn];int main()
{int n, m;scanf("%d%d", &n, &m);int x, y;CLR(Map);for (int i = 1; i <= n; i++)Map[i][i] = 1;for (int i = 0; i < m; i++){scanf("%d%d", &x, &y);Map[x][y] = 1;Map[y][x] = 1;}cin >> m;int k;map <int, int> q;for (int i = 0; i < m; i++){q.clear();cin >> k;int flag = 1;int start, num;cin >> start;int vis = start;if (k == 1){if (Map[start][start] == 1 && n == 1)printf("YES\n");elseprintf("NO\n");}else{for (int j = 1; j < k; j++){scanf("%d", &num);if (q[num])flag = 0;if (Map[vis][num] == 0)flag = 0;vis = num;q[num] = 1;}if (k != n + 1)flag = 0;if (vis != start)flag = 0;if (flag)printf("YES\n");elseprintf("NO\n");}}
}

 

  相关解决方案