素数环
import java.util.Scanner;
public class Dfs_5素数环 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] r = new int[n];
r[0] = 1;
dfs(n, r, 1);
}
private static void dfs(int n, int[] r, int cur) {
if (cur == n && isP(r[0] + r[n - 1])) {
print(r);
return;
}
for (int i = 2; i <= n; i++) {
if (check(r, i, cur)) {
r[cur] = i;
dfs(n, r, cur + 1);
r[cur] = 0;
}
}
}
private static void print(int[] r) {
for (int i = 0; i < r.length; i++) {
System.out.print(r[i] + (i == r.length - 1 ? "" : " "));
}
System.out.println();
}
private static boolean check(int[] r, int i, int cur) {
for (int e : r) {
if (e == i || !isP(r[cur - 1] + i)) return false;
}
return true;
}
private static boolean isP(int k) {
for (int i = 2; i * i <= k; i++) {
if (k % i == 0) return false;
}
return true;
}
}
public class Main {
private static int[] visit;
public static void main(String[] args) {
count(6);
}
private static void count(int n) {
int res[] = new int[n];
res[0] = 1;
visit = new int[n + 1];
visit[1] = 1;
dfs(res, 1, n);
}
private static void dfs(int[] res, int cur, int n) {
if (cur == n) {
if (check(res[0], res[n - 1])){
for (int re : res) {
System.out.printf("%d",re);
}
System.out.println();
}
}
for (int j = 2; j <= n; j++) {
if (visit[j] == 1) {
continue;
}
if (check(j, res[cur - 1])) {
visit[j] = 1;
res[cur] = j;
dfs(res, cur + 1, n);
visit[j] = 0;
res[cur] = 0;
}
}
}
private static boolean check(int x, int y) {
int num = x + y;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
困难串
public class Dfs_6_困难的串 {
public static void main(String[] args) {
int n = 10;
int l = 4;
dfs(l, n, "");
}
static int count;
private static void dfs(int l, int n, String prefix) {
for (char i = 'A'; i < 'A' + l; i++) {
if (isHard(prefix, i)) {
String x = prefix + i;
System.out.println(x);
count++;
if (count == n)
System.exit(0);
dfs(l, n, x);
}
}
}
private static boolean isHard(String prefix, char i) {
int count = 0;
for (int j = prefix.length() - 1; j >= 0; j -= 2) {
final String s1 = prefix.substring(j, j + count + 1);
final String s2 = prefix.substring(j + count + 1) + i;
if (s1.equals(s2))
return false;
count++;
}
return true;
}
}