uva 524Prime Ring Problem

来源:互联网 发布:车辆轨迹 大数据分析 编辑:程序博客网 时间:2024/06/03 09:24

原题:
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
原创粉丝点击