(hdu step 4.3.2)Prime Ring Problem(n個數成環,輸出兩兩之和為質數的所有情況),hdu4.3.2
題目:
| Prime Ring Problem |
| Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
| Total Submission(s): 467 Accepted Submission(s): 297 |
| |
Problem DescriptionA 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.
|
| Inputn (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 |
| |
| SourceAsia 1996, Shanghai (Mainland China) |
| RecommendJGShining |
題目分析:
簡單題。用DFS來做。需要注意的是第n個數還需要判斷一下和1的和是否是一個質數。需要注意的是,和上一道題相比,這一道題是一道一維的DFS題目,而上一道是一道二維的DFS題目。所以這一道題並沒有開用於包村地圖資訊的map[][]。
DFS的規則如下:
1)訪問一個鄰接的未訪問結點,並將其入棧
2)如果不能執行規則1),則出棧一個元素
3)如果不能執行規則1)2),則說明遍曆已經完成
代碼如下:
/* * b.cpp * * Created on: 2015年2月24日 * Author: Administrator */#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>using namespace std;const int maxn = 21;int value[maxn];//用來儲存最後的符合要求的結果隊列bool visited[maxn];//用於標記某一個數是否訪問過int n;/** * 判斷某一個數n是否是質數 */bool isPrime(int n){int i;for(i = 2 ; i <= sqrt(n) + 0.5 ; ++i ){//如果一個數是合數,name它必然有一個因子是<sqrt(n)的if(n%i == 0){//如果它能整除ireturn false;//說明他不是質數}}return true;//說明他是質數}/** * 輸出符合要求的結果隊列 */void printValues(){int i;for(i = 1 ; i < n ; ++i){printf("%d ",value[i]);}printf("%d\n",value[n]);}/** * 深搜 * cnt:目前搜尋到的步數 */void dfs(int cnt){//如果已經走完n步,並切蒂n個數和第1個數之和是質數if(cnt == (n+1) && isPrime(value[cnt-1] + 1)){printValues();//name這種情況是符合要求的情況,輸出所有結果}int i;for(i = 2 ; i <= n ; ++i){//遍曆每一個數,看他是否合適加入到現在這種情況的結果隊列中//如果i沒有沒訪問過&&目前結果序列的最後一個數與i的和是一個質數if((visited[i] == false) && isPrime(i+value[cnt-1])){visited[i] = true;//將i標記為已經訪問過value[cnt] = i;//將i加入到結果序列中dfs(cnt+1);//沿著該序列尋找下一個合適的數visited[i] = false;//上面一種情況已經考慮完,將i重新設定成未訪問過.用於考慮下一情況}}}int main(){int counter = 1;while(scanf("%d",&n)!=EOF){memset(visited,false,sizeof(visited));printf("Case %d:\n",counter);value[1] = 1;//序列的第1個數永遠是1visited[1] = true;dfs(2);//從第2步開始搜尋printf("\n");counter++;}return 0;}