HDU1016 DFS

简介:

                          Prime Ring Problem

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


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

Source

Recommend
JGShining
 
题解:典型DFS 做法已经标记在 程序上了
 
#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

int n,ans[22];
bool isp[45];
bool vis[45];
void dfs(int p,int x)   //p为当前第几个可行数 x为可行的数
{
    ans[p]=x;           
    vis[x]=1;
    if(p==n)             //当P等于n证明最后一个数与倒数第二个数相加为素数 只需判断是否跟1相加为素数
    {
        if(isp[ans[p]+1]) //判断最后一个数是否与1相加为素数 如果是那么该环成立 输出结果
        {
            for(int i=1; i<=n; i++)
            {
                printf("%d",ans[i]);
                if(i<n)
                    printf(" ");
                else
                    printf("\n");
            }
            return ;
        }
    }
    for(int i=1; i<=n; i++)
    {
        if(!vis[i]&&isp[ans[p]+i])
        {
            dfs(p+1,i);//符合值进入下一层搜索
            vis[i]=0;  //不符合 回溯上一层
        }
    }
    return ;
}


int main()
{
    int s=1;
    memset(isp,1,sizeof(isp));
    isp[1]=0;
    isp[0]=0;
    for(int i=2; i<=int(sqrt(40)); i++)//打出素数表
    {
        if(isp[i])
        {
            for(int j=2*i; j<=40; j+=i)
                isp[j]=0;
        }
    }
    while(scanf("%d",&n)!=EOF)
    {
        memset(vis,0,sizeof(vis));
        cout<<"Case "<<s<<':'<<endl;
        dfs(1,1);                        
        s++;
        cout<<endl;
    }

    return 0;
}

目录
相关文章
|
4月前
poj-1611-The Suspects
poj-1611-The Suspects
24 0
|
容器
POJ 3640 Conformity
POJ 3640 Conformity
50 0
|
4月前
|
算法 数据建模
Poj 3169(差分约束系统)
Poj 3169(差分约束系统)
32 0
POJ 2027 No Brainer
POJ 2027 No Brainer
104 0
POJ 1936 All in All
POJ 1936 All in All
71 0
POJ 1804
题目:http://poj.org/problem?id=1804 大意:给你一串数字,排序。求出最少的交换次数  \ 我用归并做的 #include #include using namespace std; int aa[500010],bb[500010]; long lon...
692 0
|
机器学习/深度学习
|
机器学习/深度学习