prime ring problem回溯法

这道题跟八皇后简直一样

可以这么想象,你要填充那个数组,实际上就是下楼梯。

关键是选哪一个楼梯下去。一层有多个楼梯选择。

循环,如果这个楼梯可以下去,那么记录,并下去。

如果到了底部,那么输出。

归零,装作没有来过。

Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.


 


 

Input
n (0 < n < 20).
 


 

Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.
 


 

Sample Input
  
  
6 8

#include <iostream>
using namespace std;
int a[18],num_used[18]={0},count=1;
bool is_prime(int n)
{
    for(int i=2;i<=n/2;i++)
    {
        if(n%i==0)return false;
    }
    return true;
}
bool ok(int j,int previous)
{
    bool used=true;
    for(int i=0;i<count;i++)
    {
        if(num_used[i]==j){used=false;break;}
    }

    return used;

}
void find_ring(int n,int height)
{
    for(int j=2;j<=height;j++)
    {
        if(ok((j),a[n-1])&&is_prime(j+a[n-1]))
        {
            a[n]=j;
            num_used[count++]=j;
            find_ring(n+1,height);
        }
    }
    if(n==height)
    {
        if(is_prime(a[n-1]+1)){
        for(int i=0;i<n;i++)cout<<a[i]<<" ";
        cout<<endl;}
    }
    a[n]=0;
    num_used[count-1]=0;
    count--;
}
int main()
{
    int height,ha=1;
    while(cin>>height){
    num_used[0]=1;
    a[0]=1;
    cout<<"Case "<<ha++<<":"<<endl;
    find_ring(1,height);
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值