hdu1016(简单深搜)

来源:互联网 发布:用什么软件下载电视剧 编辑:程序博客网 时间:2024/05/22 04:24

这是一个简单深搜问题,要求相邻的数之间相加为素数。采用深搜,把满足条件的值放在parent[]中。最后输出parent[].

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
68
 

Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
实现代码:
import java.util.Scanner;public class Main {static int k=0;public static void main(String[] args) {Scanner sc = new Scanner(System.in);while (sc.hasNext()) {int n = sc.nextInt();  //输入个数int[] a = new int[n];  //用来装(1~n)int[] color = new int[n]; //用来做标记int[] parent = new int[n]; //用来装结果的数组int count = 0;   //用来记录搜索个数System.out.println("Case "+(++k)+":");// 初始化数据for (int i = 0; i < n; i++) {a[i] = i + 1;color[i] = -1;//把未搜索的标记为-1parent[i] = -1;}dfs(a, color, parent, 0, count);System.out.println();}}private static void dfs(int[] a, int[] color, int[] parent, int u, int count) {color[u] = 1; //把搜索过的标记为1count++;//递归跳出的条件:次数到达了给定的的个数即数组a[]的长度;最后一个数和第一个数相加满足是素数if (count == a.length && isPrime(a[u] + a[0])) {parent[count - 1] = a[u];//把最后一个结果放到parent中print(parent);//输出结果return;}for (int v = 0; v < a.length; v++) {//满足color值为-1和当前值和下一个值相加为素数进入dfsif (color[v] == -1 && isPrime(a[v] + a[u])) {parent[count - 1] = a[u];//把满足的值放在结果数组中dfs(a, color, parent, v, count);color[v] = -1;//还原标记}}}    //输出结果private static void print(int[] parent) {for (int i = 0; i < parent.length; i++) {if (i < parent.length - 1) {System.out.print(parent[i] + " ");} else {System.out.println(parent[i]);}}}//判断是否为素数private static boolean isPrime(int num) {for (int i = 2; i * i <= num; i++) {if (num % i == 0) {return false;}}return true;}}


1 0