算法数据结构和算法分享专题算法

DFS(素数环)

2017-06-04  本文已影响37人  harvey_dong

Prime Ring Problem

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


这里解释下问题,输入一个数n 把1-n中的数组成一个环,使环上相邻的两个数相加为素数,输出所有可能的结果。

分析:

首先可以明确这是一个典型的DFS深度优先算法题。为了不出现重复的数字我们必须要有一个数组used[]标记数字是否使用,定义数组a[] 用于记录下标为k时该处的数字,因为第一个数是1 所以从下标1开始不断递归,定义一个临时变量i,i从2开始不断递增,如果a[k-1]+i是素数,并且i没有使用过就将数字used[i]标记为; a[k] = i 再搜索下一个下标k+1 处的数字。有一点,在一次递归后used为要标记为0;

#include <iostream>//HDU 1016  DFS  素数环 
#include<string.h>
using namespace std;
int a[21]={1},n,used[21]; //a[0] 永远为1
int f(int n) //判断是否为素数
{
    for(int i=2;i<=n-1;i++)
    if(n%i==0)return 0;
    return 1;
}
void dfs(int k)
{
    if(k==n&&f(a[0]+a[n-1])) //如果递归到下标n并且满足条件就找到一组正确的数据了
    {
        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(used[i]==0&&f(a[k-1]+i)) //如果i没有使用过,并且a[k-1]和i相加为素数
        {
            a[k]=i;     //记录下标的值
            used[i]=1; //标记为使用过的
            dfs(k+1);  //开始下一个下标的计算
            used[i]=0;//清除标记
        }
    }
}
int main(int argc, char *argv[])
{
    int c=1;
    while(cin>>n)
    {    
        memset(used,0,sizeof(used));
        cout<<"Case "<<c++<<":"<<endl;
        used[0]=1; //第一个数永远是1,所以下标0要标记为使用过的
        dfs(1);  //开始从下标1开始找
        cout<<endl;
    }
    return 0;
}     
上一篇 下一篇

猜你喜欢

热点阅读