HDU-1016 Prime Ring Rroblem (dfs)

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. 

 

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 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题目
#include<bits/stdc++.h>
using namespace std;
int x,mark[25],a[25];
int check(int n){
    if(n==1)
        return 0;
    if(n==2)
        return 1;
    for(int i=2;i<n;i++)
        if(n%i==0)
        return 0;
    return 1;
}
void dfs(int step){
    if(step>x&&check(mark[x]+mark[1])){
        int i;
        for(i=1;i<=x-1;i++)
            cout<<mark[i]<<" ";
        cout<<mark[i]<<endl;
    }
    for(int i=2;i<=x;i++){
        mark[step]=i;
        if(check(mark[step]+mark[step-1])&&!a[i]){
            a[i]=1;
            dfs(step+1);
            a[i]=0;
        }
    }
}
int main()
{
    int k=1;
    while(cin>>x){
        cout<<"Case "<<k++<<":"<<endl;
        memset(a,0,sizeof(a));
        mark[1]=1;
        dfs(2);
        cout<<endl;
    }
    return 0;
}

  

posted @ 2017-07-29 16:12  zzzying  阅读(175)  评论(0编辑  收藏  举报