HDU1016(简单dfs)

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   |   We have carefully selected several similar problems for you:   1010  1072  1175  1253  1181 

题意:给你一个小于20的数n,让你用1-n的数去形成一个素数环,这个素数环定义第一个数为1,任意相邻两个数之和为素数。

思路:简单dfs,标记每个数用还是不用,不满足条件时候回溯去掉标记就是了。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=30;
int a[maxn];
bool vis[maxn];
int n;
bool check(int num)
{
    for(int i=2;i*i<=num;i++)
    {
        if(num%i==0) return false;
    }
    return true;
}
void dfs(int num)//填到第i个数
{
    if(num==n&&check(a[0]+a[n-1]))
    {
        for(int i=0;i<n;i++)
        {
            if(i!=n-1) printf("%d ",a[i]);
            else printf("%d\n",a[i]);
        }
    }
    else
    {
        for(int i=2;i<=n;i++)
        {
            if(!vis[i]&&check(i+a[num-1]))
            {
                a[num]=i;
                vis[i]=true;
                dfs(num+1);
                vis[i]=false;//回溯去标记
            }
        }
    }
}
int main()
{
    while(~scanf("%d",&n))
    {
        memset(vis,false,sizeof(false));
        memset(a,0,sizeof(a));
        static int t=1;
        printf("Case %d:\n",t++);
        a[0]=1;
        dfs(1);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dl962454/article/details/80855121