1122 Hamiltonian Cycle (25 分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/acm_zh/article/details/87875935

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 V​1​​ V​2​​ ... V​n​​

where n is the number of vertices in the list, and V​i​​'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

本来做好大战一场了,以为会遇到超时啦,内存了等错误,没想到直接a了,标准的水题............... 

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
	int n,m;
	int mp[500][500]={0};
	cin >> n >> m;
	for(int i = 0;i < m;i++){
		int a,b;
		cin >> a >> b;
		mp[a][b] = mp[b][a] = 1;
	}
	int k;
	cin >> k;
	while(k--){
		int nv;
		bool flag = true;
		cin >> nv;
		int a[500]={0};
		vector<int> book(n+1,0);
		for(int i = 0;i < nv;i++){
			cin >> a[i];
		}
		if(a[0] != a[nv-1] || nv != n+1){
			cout << "NO" << endl;
		}else{
			for(int i = 1;i < nv;i++){
				if(mp[a[i-1]][a[i]] != 1){
					flag = false;
					break;
				}
				book[a[i]] = 1;
			}
			for(int i = 1;i <= n;i++){
				if(!book[i]){
					flag=false;
					break;
				}
			}
			if(flag==false){
				cout << "NO" << endl;
			}else{
				cout << "YES" << endl;
			}
		}
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/acm_zh/article/details/87875935