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.
Input
n (0 < n < 20).
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. 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
next_permunation(),可以求全排列但是超时了,这个函数以n!运行
下面是自己写的超时代码:
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<cstring>
#include<vector>
#pragma warning(disable:4996)
#define pf printf
#define sf scanf
#define ll long long int
#define ull unsigned long long int
using namespace std;
int num[25];
int n;
bool IsPrime(int num[], int n) {
int ans;
bool mark=true;
for (int i = 0; i < n&&mark; i++) {
if (i == n - 1)
ans = num[0] + num[n-1];
else
ans = num[i] + num[i + 1];
for (int j = 2; j*j <= ans&&mark;j++)
mark = ans % j ;
}
return mark;
}
ull fun(int n) {
ull ans=1;
for (int i = 1; i <= n; i++) {
ans *= i;
}
return ans;
}
int main(void) {
int count = 1;
while (cin >> n) {
cout << "Case" << count << endl;
count++;
ull sum;
for (int i = 0; i < n; i++)
num[i] = i + 1;
sum = fun(n-1);//只要从第二个开始排就好了
for (ull i = 0; i < sum; i++) {
next_permutation(num+1, num + n);//只要从第二个开始排就好了
if (IsPrime(num, n)) {
for (int j = 0; j < n; j++) pf("%d ", num[j]);
pf("\n");
}
}
}
return 0;
}
下面是深搜:
#include<cstdio>
#include<algorithm>
#include<cstring>
#pragma warning(disable:4996)
#define pf printf
#define sf scanf
int num[100100];
bool vis[100100];
int n;
int Is_Prime(int n)//x是否为素数
{
for (int i = 2; i*i <= n; i++)
if (n%i == 0)
return 0;
return 1;
}
void DFS1(int dex)//从1开始搜索
{
if (dex == n && Is_Prime(num[n - 1] + 1))//如果排到了最后一位的后一位且与第一位的和满足条件
{
pf("1");//保证第一位是1;
for (int i = 1; i<n; i++)//实际从num[]的第二位输出
pf(" %d", num[i]);//一直到n-1位
pf("\n");
}
if (dex == n) return;
for (int i = 2; i <= n; i++)
{
if (!vis[i] && Is_Prime(num[dex - 1] + i))//满足与上一位和为素数,且数字没有被使用过
{
num[dex] = i;//放入这个满足条件的数
vis[i] = 1;//标记
DFS1(dex + 1);//搜索下一位
vis[i] = 0;//回溯
}
}
}
int main()
{
int k = 1;
while (sf("%d", &n) != EOF)
{
memset(vis, 0, sizeof(vis));
num[0] = 1;
vis[1] = 1;//标记1被使用
pf("Case %d:\n", k++);
DFS1(1);
pf("\n");
}
return 0;
}