ACM

Description

Download as PDF
 

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers $1, 2, dots, 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进行一次排列要求1每次都要排在第一个位子,并且要求每相邻的两个数的和都要是一个素数。所以我们需要给出一个判断素数的函数,然后给出一个给这些数排序的函数。在这个排序的函数中我们需要注意到对于一个数我们必须没有用到过,并且这个数要与前面的数相加得到一个素数。满足条件的排列要求我们将所给的数全部用完,并且这时的最后一个数与第一个数相加的和要为一个素数。然后我们就进行递归循环下去。
程序代码:
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int n;
int a[20],vis[20];

int isp(int n)           //判断是否为素数
{
    if(n<2)
        return false;
    for (int i=2;i*i<=n; i++)
    {
        if(n % i == 0)
            return false;
    }
    return true;
}

void dfs(int s)
{
    if(s==n&&isp(a[1]+a[n]))  //递归边界。别忘了测试第一个数和最后一个数
    {
        for(int i=1; i<n; i++)
            cout<<a[i]<<" ";
        cout<<a[n]<<endl;
    }
    else
    {
        for(int i=2; i<=n; i++)
        {
            if(!vis[i]&&isp(i+a[s]))   //如果i没有用过,并且与钱一个数之和为素数
            {
                a[s+1]=i;
                vis[i]=1;              //标记
                dfs(s+1);
                vis[i]=0;              //清除标记
            }
        }
    }
}
int main()
{
    int t=0;
    while(cin>>n)
    {
        memset(vis,0,sizeof(vis));
        a[1]=1;
        if(t!=0) cout<<endl;            //一定注意输出格式
        t++;
        cout<<"Case "<<t<<":"<<endl;
        dfs(1);
    }
    return 0;
}





原文地址:https://www.cnblogs.com/xinxiangqing/p/4693013.html