素数环问题

筅森魡賤 提交于 2020-02-25 19:13:30

Problem Description

输入一个n,对1……n个数排序,1必须在第一位,相邻两个数相加要为素数(1与最后一个数相加也必须为素数)。请输出所有满足上述要求的序列

Input

n (0 < n < 20).

Output

满足要求的序列

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];
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};
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]])
            {
                vis[i] = 1;
                a[num++] = i;
                dfs(num);
                vis[i] = 0;
                num--;
            }
        }
    }
}

int main()
{
    int num; //case
    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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!