您的位置:首页 > 其它

hdu 1016Prime Ring Problem

2015-08-02 21:29 127 查看

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 33927 Accepted Submission(s): 15019



[align=left]Problem Description[/align]
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.



[align=left]Input[/align]
n (0 < n < 20).

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

6
8


[align=left]Sample Output[/align]

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
题意:输入一个小于20的整数n,从1-n的数要求组成一个环,且相邻两个点都相加为素数,用深搜方法,标记搜索过的数,还要注意路径的输出。

import java.util.Scanner;

public class Main1 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
int a[] = new int
;//用来存储每个结点的值
int color[] = new int
;//颜色,搜索标志。-1---未搜索,1为已搜索
int parent[] = new int
;//用于记录每个元素的父结点

//初始化
for(int i=0;i<n;i++){
a[i] = i+1;//结点的值
color[i] = -1;
parent[i] = -1;
}

int startNode=0;//搜索起始结点的下标
int count=0;//相当于《算法导论》中的time,此处用于代表所搜的结点数,当结点数为n时则代表搜索完成
dfs(a,color,parent,startNode,count);
}

}

private static void dfs(int[] a, int[] color, int[] parent, int u, int count) {
color[u] = 1;
count++;
//System.out.println(a[u]);
//递归鸿沟
if(count==a.length && isPrime(a[u]+a[0]) ){
parent[0] = u;
print(a,parent);
return;
}

for(int v=0; v<a.length; v++){
if(color[v]==-1 && isPrime(a[u]+a[v]) ){
parent[v] = u;
/*法1
dfs(a,color,parent,v,count);
//※※还原现场
color[v] = -1;
parent[v] = -1;
*/

//法2 做数据备份,把备份数据传进递归搜索
int color2[] = new int[a.length];
int parent2[] = new int[a.length];
for(int i=0;i<a.length;i++){
color2[i] = color[i];
parent2[i] = parent[i];
}
dfs(a,color2,parent2,v,count);
}
}

}

private static void print(int[] a, int[] parent) {
int index[] = new int[parent.length];
int p=0;
for(int i=0;i<parent.length;i++){
index[parent.length-1-i] = parent[p];
p = parent[p];
}
for(int i=0;i<index.length;i++){
if(i<index.length-1){
System.out.print(a[index[i]]+" ");
}else{
System.out.println(a[index[i]]);
}
}
}

private static boolean isPrime(int n) {
if(n==2){
return true;
}
for(int i=2;i*i<=n;i++){
if(n%i==0){
return false;
}
}
return true;
}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: