深搜經典題型 hdu1016 Prime Ring Problem

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

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K

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

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#define Maxn 40

using namespace std;


int prime[Maxn],n;
int a[21],vis[21];
int Is_prime(int x)
{
    //判斷是不是素數
    for(int i=2;i<x;i++)
    {
        if(x%i==0)
            return 0;
    }
    return 1;
}
void Type()
{
    //素數打表
    for(int i=1;i<Maxn;i++)
    {
        if(Is_prime(i))//判斷是不是素數
            prime[i]=1;
    }
}
void Print(int k)
{
    //輸出數組a
    for(int i=1;i<k;i++)
    {
        if(i!=k-1)
            printf("%d ",a[i]);
        else
            printf("%d\n",a[i]);
    }
}
void dfs(int x,int k)
{
    //x用來表示遞歸次數(就是符合條件的次數),k用來計數以便往數值a裏面填值
    if(x==n&&prime[1+a[x]])
    {
        //判斷是不是到了最後一個數 && 最後一個數和第一個數的和是素數
        Print(k);
        return ;
    }
    for(int i=2;i<=n;i++)
    {
        if(!vis[i]&&prime[i+a[x]])
        {
            vis[i]=1;
            a[k]=i;      //往數組裏填數
            dfs(x+1,k+1);
            vis[i]=0;    //回溯
        }
    }
}
int main()
{
    Type();
    int t=0;
    while(~scanf("%d",&n))
    {
        memset(a,0,sizeof(a));
        memset(vis,0,sizeof(vis));
        a[1]=1;vis[1]=1;t++;
        printf("Case %d:\n",t);
        dfs(1,2);
        printf("\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章