HDU-1016-Prime Ring Problem
Posted 1625--h
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU-1016-Prime Ring Problem相关的知识,希望对你有一定的参考价值。
Problem Description
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.
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.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
6
8
Sample Output
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
分析:
1. 从1-n个数组以1为开头,构成一个数列,保证相邻两数的和为质数,并且首尾之和也同样满足,我们可以遍历整个数组来检测这个情况是否满足。
2.n的最大值是20,可想而知上述方法在n等于20的时候复杂度之高,是不可行的,我们要在过程中直接筛掉一部分,第一个可以想得到的就是,要是质数,必须是奇数,两数之和为奇数,所以n必须是偶数才可以。
3.在构成数列的时候,如果满足相邻两数之和不为奇数则直接判输。
4.依然要遍历每一种可能,只是我们不把数组一次性建好,而是填充一个元素,检测一下是否满足条件,满足则继续,不满足则判输。
5.当数组填充满了的时候,要检测首尾数字是否满足情况。
6.如果有一种情况满足则直接输出。
优化:n数值小,判断是否是质数可以直接用数组来保存。
1 #include <iostream> 2 using namespace std; 3 int a[20]; 4 bool isprime[38] = { 5 0,1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 6 }; 7 8 void print(int n) 9 { 10 for (int i = 0; i < n; i++) 11 { 12 if (i==0) 13 printf("%d", a[i]); 14 else 15 { 16 printf(" %d", a[i]); 17 } 18 } 19 printf(" "); 20 } 21 bool ok(int cur) 22 { 23 if (!isprime[a[cur] + a[cur - 1]]) 24 return false; 25 for (int i = 1; i < cur; i++) 26 { 27 if (a[i] == a[cur]) 28 return false; 29 } 30 return true; 31 } 32 void dfs(int n, int cur) 33 { 34 if (n & 1) 35 return; 36 if (cur == n) 37 { 38 if (isprime[1 + a[cur - 1]]) 39 print(n); 40 } 41 else 42 { 43 for (int i = 2; i <= n; i++) 44 { 45 a[cur] = i; 46 if (ok(cur)) 47 dfs(n, cur + 1); 48 } 49 } 50 } 51 int main() 52 { 53 int n,k=0; 54 while (cin >> n) 55 { 56 k++; 57 printf("Case %d: ", k); 58 a[0] = 1; 59 dfs(n, 1); 60 printf(" "); 61 } 62 return 0; 63 }
以上是关于HDU-1016-Prime Ring Problem的主要内容,如果未能解决你的问题,请参考以下文章