HDUOJ1016 Prime Ring Problem

來源:互聯網
上載者:User

  Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8087    Accepted Submission(s): 3620
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.

 

  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

 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 【解題思路】素數環是典型的DFS題目,DFS函數的參數為(int c, int cnt), c代表遍曆時所在環上節點的數,cnt代表結點個數。當節點個數位n時並且環末節點 和首節點相加也為素數則列印環。 

根據本題總結dfs的主要步驟和方法:

1. 找搜尋出口條件,即搜尋到最深層時的操作

2.  Dfs採用遞迴搜尋,在遍曆後返回時標記已經遍曆的節點

3. 注意允入準則的滿足

4. 畫出遞迴搜尋圖查看函數是否滿足要求

5. 注意回溯的條件,適當的時候需要剪枝

 

 

 

//============================================================================ // Name : HDUOJ1016.cpp // Author : Weisi Shi // Version : // Copyright : Weisi Shi // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int n; bool p[41]; int circle[21]; bool visit[21]; void prime() { int i, j; memset(p, true, sizeof(p)); for (i = 2; i < 41; ++i) { for (j = 2; i * j < 41; ++j) { p[i * j] = false; } } } void dfs(int c, int cnt) { int i, j; if (cnt == n && p[circle[1] + circle[n]]) { for (i = 1; i < n; ++i) cout << circle[i] << " "; cout << circle[n] << endl; } for (j = 1, i = c + j; j <= n; i++, j++) { if (p[i] && !visit[j]) { circle[cnt + 1] = j; visit[j] = true; dfs(j, cnt + 1); visit[j] = false;//回溯 } } } int main() { int c = 1; prime(); while (cin >> n) { memset(visit, false, sizeof(visit)); cout << "Case " << c++ << ":" << endl; visit[1] = true; circle[1] = 1; dfs(1, 1); cout << endl; } return 0; }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.