1509: Hamiltonian Cycle
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
![]() | 3s | 8192K | 400 | 88 | 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 il, v il} 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:n1
%
n2
%
where ni is the number of vertices and
are integers between 1 and n indicating that there exists an edge between vertex uih and uil
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
This problem is used for contest: 149
#include<iostream>
#include<algorithm>
using namespace std;
int n,map[100][100],vis[100],res[100];
bool flag;
void dfs(int step,int num)
{
if(flag) return ;
if(step==n)
{
if(map[num][1])
{
flag=true;
printf("%d",res[1]);
for(int i=2;i<=n;i++) printf(" %d",res[i]);printf(" %d",res[1]);
printf("/n");
}
return ;
}
vis[num]=1;
for(int i=1;i<=n;i++)
{
if(map[num][i]&&vis[i]==0)
{
res[step+1]=i;
dfs(step+1,i);
}
}
vis[num]=0;
}
int main()
{
while(scanf("%d",&n)==1)
{
getchar();
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
char str[10];
while(gets(str))
{
if(str[0]=='%') break;
map[str[0]-'0'][str[2]-'0']=map[str[2]-'0'][str[0]-'0']=1;
}
if(n<3) {printf("N/n");continue;}
flag=false;
res[1]=1;
dfs(1,1);
if(!flag) printf("N/n");
}
return 0;
}