1509: Hamiltonian Cycle(深搜)

Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 427 99 Standard

A few definitions first:

Definition 1
A graph G = (V, E) is called ``dense'' if for each pair of non-adjacent vertices u and v , where n = | V | and denotes the degree of the vertex .
Definition 2
A ``Hamiltonian cycle'' on G is a sequence of vertices ( ) such that for all and { v i l , v i l } is an edge of G.

The problem is: write a program that, given a dense graph G = (V; E) as input, deter- mines whether G admits a Hamiltonian cycle on G and outputs that cycle, if there is one, or outputs ``N '' if there is none.

Input

A file containing descriptions of graphs, each one ending with a %, in the form:

n 1

%

n 2

%

where n i is the number of vertices and are integers between 1 and n indicating that there exists an edge between vertex u i h and u i l

Output

The output file must contain the sequence of vertices that form a Hamiltonian cycle in the form:

or containing:

N

Sample Input

 

4
1 2
2 3
2 4
3 4
3 1
%
6
1 2
1 3
1 6
3 2
3 4
5 2
5 4
6 5
6 4
%

Sample Output

 

1 2 4 3 1
1 2 3 4 5 6 1




#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int map[100][100];
int n,vis[100];
char str[10];
int ans[100];
int j;
bool flag;
void dfs(int x,int y)//第x层解答树,第y个取值
{
ans[x]=y;//先进行处理
vis[y]=1;
if(x==n)
{
if(map[ans[x]][ans[1]])
{
cout<<ans[1];
for(int i=2;i<=n;i++)
cout<<" "<<ans[i];
cout<<" "<<ans[1]<<endl;
flag=true;
return;
}
}
else
{
for(int i=1;i<=n;i++)
{
if(map[y][i]&&!vis[i])
{
dfs(x+1,i);
}
}
}
vis[y]=0;//注意
}
int main()
{
int i;
while(cin>>n)
{
getchar();
memset(vis,0,sizeof(vis));
memset(map,0,sizeof(map));
while(1)
{ gets(str);
if(strcmp(str,"%")==0) break;
int x=str[0]-'0';
int y=str[2]-'0';
map[x][y]=1;
map[y][x]=1;
}
flag=false;
if(n<3)
{ cout<<"N"<<endl;
continue;
}
else
{ dfs(1,1);
if(!flag)
cout<<"N"<<endl;
}
}
return 0;
}

你可能感兴趣的:(1509: Hamiltonian Cycle(深搜))