HDU 1016 dfs+回溯

来源:互联网 发布:app 是什么软件 编辑:程序博客网 时间:2024/05/16 04:32

Prime Ring Problem

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

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

素数环算是经典的问题了,主要是用回溯法。如满足条件就继续,如不满足就不继续。但是不能就简单return回去,因为在这一层用过数在上一层可以继续用,因此,开一个vis数组,记录数组i用过没有,开始用vis[i] = 1,表示用过,在第Z层里由于存在for循环,因此i++后是不可能再取到i的。在递归的下一层Z+1,由于已经设置了vis[i] = 1,因此下一层是不会填i的。而过后又vis[i] = 0;表示又可以在和Z上一层Z-1的另一阶X中递归用到。重复这个过程,整个递归树只执行有效的递归,一旦出现不符合要求的值时就返回。

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int prime[50];bool p[50];int vis[50];int a[40];int Ai(int n){    int i,j,k = 0;    for(i = 2;i<=n*2;i++)        p[i] = true;    for(i =  2;i<=n*2;i++){        if(p[i])            prime[k++] = i;        for(j = 2*i;j<=n*2;j+=i)            p[j] = false;    }    return k;}void dfs(int n,int cur){    int i,j;    bool ok,ok1;    if(cur == n&&p[a[0]+a[n-1]]){        printf("%d",a[0]);        for(i = 1;i<n;i++)            printf(" %d",a[i]);        printf("\n");        return ;    }    for(i = 2;i<=n;i++)        if(!vis[i]&&p[i+a[cur-1]]){            a[cur] = i;            vis[i] = 1;            dfs(n,cur+1);            vis[i] = 0;        }}int main(){    Ai(40);    int i,j;    int n,cnt = 1;    while(scanf("%d",&n)!=EOF){        memset(vis,0,sizeof(vis));        a[0] = 1;        printf("Case %d:\n",cnt++);        dfs(n,1);        printf("\n");    }    return 0;}
0 0
原创粉丝点击