DFS(素数环)

作者: harvey_dong | 来源:发表于2017-06-04 10:42 被阅读37次

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;
}     

相关文章

  • DFS(素数环)

    Prime Ring Problem Problem Description A ring is compose ...

  • 素数环问题

    素数环是一个计算机程序问题,指的是将从1到n这n个整数围成一个圆环,若其中任意2个相邻的数字相加,结果均为素数,那...

  • DFS及其应用

    内容概要: DFS类的实现 DFS求解连通分量 DFS求解点对之间的一个路径 DFS判定无环图和二分图 相关概念 ...

  • 走环(入门dfs)

    这道题是我在看DFS的时候偶然发现有个大佬(https://blog.csdn.net/qq_41003528/a...

  • Currency Exchange POJ - 1860

    题意:币种兑换寻找是否有正环 计算公式 (money - Cost) * Rate 思路:spfa_dfs 判正环

  • BFS和DFS随笔

    BFS和DFS BFS和DFS视频讲解-正月点灯笼 BFS核心点是用队列存放当前搜索的点 用在有环图的时候需要存放...

  • 7-4 素数环

    https://vjudge.net/problem/UVA-524 就是一个简单的回溯法 注意1是固定的 所以传...

  • 回溯法求解素数环

  • 无向图 图的表示方法:邻接表 dfs和bfs的区别:dfs是用栈,bfs用队列 有向图 有向无环图(DAG): 不...

  • 图论

    基于DFS求无向连通图的环 对于每一个连通分量,如果无环则只能是树,即:边数=结点数-1 只要有一个满足 边数 >...

网友评论

    本文标题:DFS(素数环)

    本文链接:https://www.haomeiwen.com/subject/mdvmfxtx.html