PTA汉密尔顿回路

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

输入格式:

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

其中 n 是回路中的顶点数, V i 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


思路: 将边用数组存储起来,判断回路里两条边之前是否连通并且除出发点外其余点只出现一次。如果给定的回路里点的个数不等于n+1,直接NO
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
#define N 205
int edge[N][N];
int main(){
	int n,m,x,y;
	cin >> n >> m;
	memset(edge,0,sizeof(edge));
	for(int i=0;i<m;i++){
		cin >> x >> y;
		edge[x][y] = 1;
		edge[y][x] = 1;
	}
	int t,vis[n+1];
	memset(vis,0,sizeof(vis));
	cin >> t;
	while(t--){
		int cnt,pre,flag=1,start;
		cin >> cnt;
		cin >> start; vis[start]=1;pre = start;
		
		for(int j=1;j<cnt;j++){
			cin >> x;
			if(!edge[pre][x]) flag = 0;
			// 判定条件要注意
			if(vis[x]&&(j<cnt-1||x!=start)) flag = 0;
//			if(vis[x]&&x!=start||!edge[pre][x]) flag = 0;
			vis[x]=1;
			pre = x;
		}
		if(cnt!=n+1) flag = 0;
		if(flag) cout<< "YES" << endl;
		else cout << "NO" << endl;
		memset(vis,0,sizeof(vis));
	} 
	return 0;
}

发布了63 篇原创文章 · 获赞 34 · 访问量 6548

猜你喜欢

转载自blog.csdn.net/SinclairWang/article/details/104046468
PTA