1122. Hamiltonian Cycle (25)

1122. Hamiltonian Cycle (25)

时间限制
300 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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
题意:给出一个含有N顶点M条边的图,再给出k条路线,判断路线是否是 遍历了所有顶点

分析:1.明显n要等于N+1才能不重复地包含所有顶点

           2.V1值要和Vn值相同 否则无法构成环路

           3.需要对路线数一遍以确定有没有重复or漏点

           4.路线要合法,即点与点间要有连线

代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n,m,k,a,b;
	cin>>n>>m;	
	vector<vector<int> > map(300);
	for(int i=1;i<=m;i++)
	{
		cin>>a>>b;
		map[a].push_back(b);
		map[b].push_back(a);
	}
	cin>>k;
	while(k--){
		cin>>a;
		int list[300]={0},check[300]={0};
		for(int i=0;i<a;i++)
			cin>>list[i];	
		if(a!=n+1 || list[0]!=list[a-1]){//对应分析 1,2 
			cout<<"NO"<<endl;
			continue;
		}
		else {
			int i,j;
			for(j=1;j<=n;j++){//分析3 
				if(!check[list[j]]) check[list[j]]++;
				else break;
			}
			for(i=1;i<=n;i++)//分析4 
				if(find(map[list[i]].begin(),map[list[i]].end(),list[i-1])==map[list[i]].end())
					break;
			if(j!=n+1 || i!=n+1) cout<<"NO"<<endl;
			else cout<<"YES"<<endl;
		}
	}
}

结尾:感觉很简单的一道题,十几二十分钟就敲出来了但是debug弄了近两个小时,有点怀疑人生。

           判断道路合法性的时候find()==map[list[i]].end() 写成 find()==map[i].end(),导致第二个测试点一直过不去。开始以为是分析缺了一个方面,想了半天还是觉得四点就够了,然后自己写数据测试(如下),结果发现图没联通的时候也会出现yes,以为是find的问题,又去看了find的源码 感觉用法很ok。但是又实在想不出为什么会这样,总感觉思路没问题代码就没问题了,然后怀疑在map[i]等于空的情况下会有一些奇妙的判断(那时已经混沌了),于是直接加了empty()的判断。自信满满地交了上去,结果……之后又在想会不会是0、负数之类的又饶了一大圈,最后放弃。                              第二天起来,一眼发现了问题_(:з」∠)_

3 1

1 2

10

4 1 2 3 1 (yes)

4 1 3 2 1 (no)

4 2 1 3 2 (yes)

4 2 3 1 2 (yes)

4 3 1 2 3 (no)

4 3 2 1 3 (no)



posted @ 2017-12-26 16:12  九大于七  阅读(384)  评论(0编辑  收藏  举报