hdu1016 Prime Ring Problem(dfs)

来源:互联网 发布:js中json转数组 编辑:程序博客网 时间:2024/05/22 08:09

搜索的水很深啊,还是先从简单的题做起吧

题目很容易理解,给定大于0小于20的数字n;

求出由n个数字组成的环;

该环每相邻的两个数之和为素数

这n个数字有1,2....n-1,n组成,不能有重复!

每个环从都1开始

输出按照字典序从小到大输出所有可能;

原题要求:

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29191    Accepted Submission(s): 13001


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
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
代码

#include<iostream>#include <math.h>#include <string.h>using namespace std;int a[22], n, vist[22];int is_prime(int n){    int m = (int)sqrt(n);    for (int i = 2; i <= m; i++)        if (n % i == 0)            return 0;    return 1;}void difs(int cur){    if (cur == n && is_prime(a[0] + a[n - 1])) {        for (int i = 0; i < n - 1; i++)            cout << a[i] << " ";        cout << a[n - 1] << endl;    } else {        for (int i = 2; i <= n; i++)            if (!vist[i] && is_prime(i + a[cur - 1])) {                a[cur] = i;                vist[i] = 1;                difs(cur + 1);                vist[i] = 0;            }    }}int main(){    int i, j = 1;    while (cin >> n) {        memset(vist, 0, sizeof(vist));        for (i = 0; i < n; i++)            a[i] = i + 1;        cout << "Case " << j << ":" << endl;        difs(1);        cout << endl;        j++;    }    return 0;}


0 0