HDU-1016 Prime Ring Problem (DFS)

    题目:HDU 1016

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016

    题目:

Prime Ring Problem

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


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.

HDU-1016 Prime Ring Problem (DFS)_第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
 

     这道题目是非常经典的dfs,题意是给一个n(n<20),用1~n构建素数环,使任意两个相邻整数之和为素数,所以直接用dfs来做,因为n取值范围是20,我们直接把40以内的12个素数打印出来,因为以1开始,旁边的数和1的和必须是素数而且和1不同,那2肯定不合适,所以就变成了11个素数(能省则省嘛~),之后就是深搜,如果满足素数换,那么就输出,不满足就回溯,我做这道题目时卡在了将状态回归,也就是在递归之后消除上次递归对下次递归影响这里,虽然卡了很久但最后搞懂之后还是挺有收获的,不多说废话,自己感觉一下就知道了。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<math.h>
using namespace std;
const int maxn=25;
int n;
int prime[11]={3,5,7,11,13,17,19,23,29,31,37};  //打表
int visit[maxn];                                //标记是否走过
int ans[maxn];                                  //存储答案(也就是序列)
int IsPrime(int x){                             //判断是否是素数,仅仅用于判断队尾和队首和是不是素数
    if(x==1) return 0;
    for(int i=2;i<=sqrt((double)x);i++)
        if(x%i==0) return 0;
        return 1;
}
void dfs(int x){                                //递归
    if(x==n) {                                  //满足条件输出答案
    if(IsPrime(ans[n-1]+ans[0])){
        for(int i=0;i<n-1;i++)
            printf("%d ",ans[i]);
            printf("%d\n",ans[n-1]);
    }
    }
    else{
        for(int i=0;prime[i]-ans[x-1]<=n && x<n;i++){ //循环
            int temp=prime[i]-ans[x-1];
            if(temp>1 && temp<=n){
                if(visit[temp]==0){
                    ans[x]=temp;
                    visit[temp]=1;
                    dfs(x+1);
                    visit[temp]=0;                //消除标记影响
            }
        }
        }
    }
    return;
}
int main(){
    int count=0;
    while(cin>>n){
        printf("Case %d:\n",++count);
        memset(ans,0,sizeof(ans));
        memset(visit,0,sizeof(visit));
        ans[0]=1;
        visit[1]=1;
        dfs(1);
        printf("\n");
    }
    return 0;
}

     好好学习,天天向上~~~

你可能感兴趣的:(DFS,杭电,HDU-1016)