Example 7-4 Prime ring UVa524

Source: Internet
Author: User

1. Title Description: Click to open the link

2. Solving ideas: The problem is solved by backtracking. First, all primes in the 2*n range are generated to facilitate subsequent judgment. Next try to fill in each bit, if the number I satisfies is not used and it is the sum of the previous item is a prime, then it can be used, while marking it has been used, recursively looking for cur+1, exit when the use of the mark.

3. Code:

#define _crt_secure_no_warnings #include <iostream> #include <algorithm> #include <string> #include <sstream> #include <set> #include <vector> #include <stack> #include <map> #include < queue> #include <deque> #include <cstdlib> #include <cstdio> #include <cstring> #include < cmath> #include <ctime> #include <functional>using namespace std; #define N 20int vis[2*n],a[n],flag[n]; int n;void init ()//generates primes {int m = sqrt (2*n + 0.5), for (int i = 2; I <= m;i++) for (int j = i*i; J < 2 * N; j + = i) if (! VIS[J]) vis[j] = 1;}  void dfs (int cur) {if (cur = = n&&!vis[a[0] + a[n-1]) {for (int i = 0; i < n; i++) printf ("%d%c", a[i], i = = N- 1? ' \ n ': ');} else for (int i = 2; I <= n;i++) if (!flag[i] &&!vis[i + a[cur-1]]) {a[cur] = i;flag[i] = 1;//set use flag DFS (cur + 1); Flag[i] = 0;//clear Use flag}}int main () {//freopen ("T.txt", "R", stdin), int rnd = 0;init (), while (~SCANF ("%d", &n)) {if (rn d) cout << endl;printf ("case %d:\n ", ++rnd); memset (A, 0, sizeof (a)); A[0] = 1;memset (flag, 0, sizeof (flag));d FS (1);} return 0;}

Example 7-4 Prime ring UVa524

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.