hdu.1016 Prime Ring Problem

import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { int n,count = 0; int prime[] = new int[30];; Scanner input = new Scanner(System.in); while (input.hasNextInt()) {    count++;
        n = input.nextInt(); Arrays.fill(prime, 0);
        prime[0] = 1; System.out.println("Case "+count+":");
        find(n, 1, prime); System.out.println(); } } private static void find(int n,int cur,int[] prime) {
    // TODO Auto-generated method stub
 if (cur == n && is_prime(prime[0] + prime[cur-1])) { for (int i = 0; i < n; i++) { if (i == 0) { System.out.print(prime[i]); } else { System.out.print(" "+prime[i]); } } System.out.println(); } else { for (int i = 2; i <= n; i++) { boolean is = true;
            prime[cur] = i; for (int j = 0; j < cur; j++) { if (prime[j] == i) {
                    is = false; break; } } if (is_prime(prime[cur] + prime[cur - 1]) && is) {
                find(n, cur+1, prime); } } } } private static boolean is_prime(int n) {
    // TODO Auto-generated method stub
for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return  false; } } return true; } }
dfs,不需要剪剪枝。

你可能感兴趣的:(hdu.1016 Prime Ring Problem)