joj 1509

 1509: Hamiltonian Cycle


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s 8192K 467 113 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 ilv 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 


Submit / Problem List / Status / Discuss





这是一个哈密尔顿回路问题,其中n必须大于2,因为回路至少要有三个点


#include<cstdio>
#include<string.h>


bool selected;
int map[100][100];
int temp[100];
int store[100];
int n;
void dfs(int x,int y)
{
    if(selected)return ;
    if(y>n&&map[store[1]][store[n]])
    {
        for(int i=1;i<=n;i++)printf("%d ",store[i]);
        printf("1\n");
        selected=true;
        return ;
    }
    for(int i=1;i<=n;i++)
    {
        if(map[x][i]&&!temp[i])
        {
            temp[i]=1;
            store[y]=i;
            dfs(i,y+1);
            temp[i]=0;
        }
    }
}
int main()
{
    while(scanf("%d",&n)==1)
    {
        getchar();
        memset(map,0,sizeof(map));
        memset(temp,0,sizeof(temp));
        char str[4];
        gets(str);
        while(strcmp(str,"%")!=0)
        {
            int a = str[0] - '0';
            int b = str[2] - '0';
            map[a][b] = map[b][a] = 1;
            gets(str);
        }
        if(n<3)
        {
            printf("N\n");
            continue;
        }
        else//此时的else必须与if连在一起因为n<3时候也必须要有输入!!!
        {
            selected=false;
            store[1]=1;
            temp[1]=1;
            dfs(1,2);
            if(!selected)printf("N\n");
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值