uva 524 Prime Ring Problem

原题:
A ring is composed of n (even number) circles as shown in diagram.Put natural numbers 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 ≤ 16)
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. You are to write a program that completes above process.
Sample Input
6
8
Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

中文:
给你一个数n,让你从1到n这这些数排列,使得相邻的两个数的和是个素数,最后一个数和第一个数和也是素数。

#include <bits/stdc++.h>
using namespace std;
int p[1001];
bool tag[1100];
int get_prime()
{
    int cnt=0;
    for(int i=2;i<1100;i++)
    {
        if(!tag[i])
            p[cnt++]=i;
        for(int j=0;j<cnt&&p[j]*i<1100;j++)
        {
            tag[i*p[j]]=1;
            if(i%p[j]==0)
                break;
        }
    }
    return cnt;
}
int a[100];
bool vis[100];
int n;
void dfs(int x)
{
    if(x==n&&!tag[a[1]+a[x]])
    {
        for(int i=1;i<=n;i++)
        if(i!=n)
            cout<<a[i]<<" ";
        else
            cout<<a[i]<<endl;
    }
    else
    {
        for(int i=2;i<=n;i++)
        {
            if(!vis[i]&&!tag[a[x]+i])
            {
                vis[i]=true;
                a[x+1]=i;
                dfs(x+1);
                vis[i]=false;
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    get_prime();
    int k=0;
    while(cin>>n)
    {
        if(k)
            cout<<endl;
        memset(vis,false,sizeof(vis));
        a[1]=1;
        vis[1]=true;
        cout<<"Case "<<++k<<":"<<endl;
        dfs(1);
    }
    return 0;
}

解答:
在刘汝佳的紫书上无意间翻到这道题目,感慨万千,因为我记得自己刚进入acm的时候学回溯法,第一道是骑士巡游,第二道题就是它!只不过是在杭电上面交过的,现在已经过了2年多了,没事做题只不过是为了让自己能够记住和熟悉以前学过的代码,权当是纪念了~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值