PAT甲级 1122 Hamiltonian Cycle (25 分)图论

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

解析: 这题很简单,只需多注意是否是简单环的判断情况即可。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const int N = 201,inf = 0x7fffffff;
int edge[N][N];

int main(){
	fill(edge[0],edge[0]+N*N,inf);
	int n,m,k,num,a,b;
	cin>>n>>m;
	for(int i=0;i<m;i++){
		cin>>a>>b;
		edge[a][b] = edge[b][a] = 1;
	}
	cin>>k;
	for(int i=0;i<k;i++){
		cin>>num;
		vector<int> vec(num),vst(n+1,0);
		for(int j=0;j<num;j++)
			cin>>vec[j];
		if(num != n+1){
			cout<<"NO"<<endl;
			continue;
		}	
		if(vec[0] != vec[vec.size()-1]){
			cout<<"NO"<<endl;
			continue;
		}
		int a,b,flag = 0;
		for(int j=0;j<vec.size()-1;j++){
			a = vec[j];
			b = vec[j+1];
			if(edge[a][b] == inf){
				flag = 1;
				break;
			}
			vst[a] = 1;
		}
		vst[b] = 1;
		if(flag == 1)
			cout<<"NO"<<endl;
		else{
			int flag1 = 0;
			for(int j=1;j<vst.size();j++)
				if(vst[j] == 0){
					flag1 = 1;
					break;
				}
			if(flag1 == 1)
				cout<<"NO"<<endl;
			else
				cout<<"YES"<<endl;	
		}	
	}
		
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/85344636
今日推荐