HDU 1016 prime ring problem Prime Ring

Source: Internet
Author: User
Problem descriptionA ring is compose of N circles as shown in digoal. put Natural Number 1, 2 ,..., N into each circle separately, and the sum of numbers in two adjacent circles shoshould be a prime.

Note: The number of First Circle shoshould always be 1.InputN (0 <n <20 ).

 

OutputThe 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 abve 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
// Backtracking (DFS traversal solution tree) # include <iostream> using namespace STD; int N, CNT = 1; int vis [21], a [21]; // prime number table to accelerate subsequent judgment of int primelist [38] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; void DFS (INT cur) {If (cur = N & primelist [A [0] + A [n-1]) // recursive boundary, do not forget to test the first and last number {cout <A [0]; for (INT I = 1; I <n; ++ I) cout <"" <A [I]; // print format of the question. Note that the last digit is printed without a space. cout <Endl ;} else For (INT I = 2; I <= N; + + I) // try to place each number IIF (! Vis [I] & primelist [I + A [cur-1]) // if u has not been used, and the sum of the preceding number is a prime number {A [cur] = I; // put the number in a vis [I] = 1; // set the use flag DFS (cur + 1); // recursively call vis [I] = 0; // remember to change the flag back to clear the flag !}} Int main () {A [0] = 1; // The position of 1 remains unchanged while (CIN> N) {memset (VIS, 0, sizeof (VIS )); // tag the array to clear cout <"case" <CNT ++ <":/N"; DFS (1); cout <Endl ;}return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.