Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 43391 Accepted Submission(s): 19262
Problem Description
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.
Note: the number of first circle should always be 1.
![](https://i-blog.csdnimg.cn/blog_migrate/427b1dd2282412709d583cc17eda983e.gif)
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.
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 <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <iostream>
#include <assert.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
#define PI acos(-1.0)
const int M = 4e2 + 10;
bool primes[M];
bool vis[25];
int ans[25];
int n;
void isprime()
{
memset(primes, true, sizeof(primes));
primes[0] = primes[1] = 0;
for (int i = 2; i <= 400; i++) {
if (!primes[i]) continue;
for (int j = i * i; j <= 400; j += i)
primes[j] = false;
}
}
void dfs(int id)
{
if (id > n) {
int x = ans[1] + ans[n];
if (!primes[x]) return;
printf("1");
for (int i = 2; i <= n; i++)
printf(" %d", ans[i]);
printf("\n");
}
for (int i = 2; i <= n; i++) {
if (vis[i]) continue;
int x = ans[id - 1] + i;
if (!primes[x]) continue;
vis[i] = 1;
ans[id] = i;
dfs(id + 1);
vis[i] = 0;
}
}
int main()
{
isprime();
int cascnt = 0;
while (cin >> n) {
memset(vis, 0, sizeof(vis));
memset(ans, 0, sizeof(ans));
ans[1] = 1;
vis[1] = 1;
printf("Case %d:\n", ++cascnt);
dfs(2);
printf("\n");
}
return 0;
}