首页 > 编程语言 > 详细

C语言编程练习50:素数环

时间:2021-02-07 23:10:29      阅读:30      评论:0      收藏:0      [点我收藏+]
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.

技术分享图片

Inputn (0 < n < 20).
OutputThe 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
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


#include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <list>
#include <cstdlib>
#include <cstring>
using namespace std;

int n,a[30],vis[30];//vis是标记数组
int prime[40]={0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0};//1-40素数表,素数用1标记
void dfs(int num)
{
    if(num==n&&prime[a[num-1]+a[0]])
    {
        for(int i=0;i<num-1;i++)
        {
            printf("%d ",a[i]);
        }
        printf("%d\n",a[num-1]);
    }
    else
    {
        for(int i=2;i<=n;i++)
        {
            if(vis[i]==0&&prime[i+a[num-1]])//判断i的标记和素数表
            {
                vis[i]=1;
                a[num++]=i;
                dfs(num);
                vis[i]=0;//回溯标记和num
                num--;
            }
        }
    }
    
}
int main()
{
    int num;
    num=0;
    while(cin>>n)
    {
        memset(vis,0,sizeof(vis));
        num++;
        printf("Case %d:\n",num);
        a[0]=1;
        dfs(1);
        printf("\n");
    }
    return 0;
}

 参考:https://blog.csdn.net/feng_zhiyu/article/details/75576867

    https://blog.csdn.net/gjs935219/article/details/81868331

C语言编程练习50:素数环

原文:https://www.cnblogs.com/FantasticDoubleFish/p/14386396.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!