🍑 OJ专栏
🍑 HDOJ 1016 Prime Ring Problem
输入
6
8
输出
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 个数组一个成环,要求相邻的两数和 为 质数
🍑 思路
🍤 DFS 从第 1 位开始搜(不符合条件的直接不搜)
🍤 预处理素数表 O(n),判断素数 O(1)
🍑 AC code
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static int n, N = 30;
static boolean[] st = new boolean[N];// 记录每个数是否已经使用
static int[] a = new int[N];//记录环序列
static boolean[] p = new boolean[100];// 素数筛数组
static int[] primes = new int[N];// 素数数组 (flase表示素数)
static int idx;// 记录有几个素数
// 线性筛法初始化素数数组
static void init()
{
p[0] = true;
p[1] = true;
for (int i = 2; i < 100; i++)
{
if (!p[i])
primes[idx++] = i;
for (int j = 0; primes[j] * i < 100; j++)
{
p[i * primes[j]] = true;
if (i % primes[j] == 0)
break;
}
}
}
// x 表示
private static void dfs(int x, int cnt)
{
if (cnt == n)
{
int t = a[cnt] + a[1];
if (!p[t])// 是质数
{
for (int i = 1; i < n; i++)
// System.out.printf("%d ",a[i]); // TLE?
System.out.printf(a[i] + " ");// PE?
System.out.println(a[n]);
}
}
for (int i = 2; i <= n; i++)
{
if (st[i] || p[i + x])
continue;
st[i] = true;// 表示当前数以选
a[++cnt] = i;
dfs(i, cnt);
cnt--;
st[i] = false;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int cnt = 1;
init();// 预处理质数数组
while (sc.hasNext())
{
n = sc.nextInt();
Arrays.fill(st, false);
a[1] = 1;
// if(cnt != 1)
// System.out.println();
System.out.println("Case " + (cnt++) + ":");
dfs(1, 1);
System.out.println();
}
}
}