杭电1016(DFS+素数环)

Prime Ring Problem(难度:1)

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

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.
杭电1016(DFS+素数环)_第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

思路:

题意:输出一个素数环,第一个数字必须为1,存在多个按字典序由小到大输出。每个测试样例后有空行。

方法:深度优先搜索。

AC代码:

#include
#include
using namespace std;

int n;
int primecircle[22];
int vis[22];
int num;

//判断是否为素数 
bool isprime(int a)
{
    for(int i=2;i<=a/2;i++)
    {
        if(a%i==0) return false;
    }
    return true;
}

//深搜 
void dfs(int a)//a为当前已经放入环中的数字 
{
    //若已经放入了n个数,且最后一个数和第一个数(1)相加为素数 
    if(n==num&&isprime(a+1))
    {
        for(int i=1;i<=n;i++)
        {
            //最后一个数后没有空格 
            if(i!=n) cout<" ";
            else cout<return;//返回,继续枚举下一组解 
    }
    for(int i=2;i<=n;i++)//放入一个数 
    {
        //当前的数和放入的数相加为素数
        if(vis[i]==0&&isprime(a+i))
        {
            vis[i]=1;//标记为已经访问过 
            num++;//数量加1 
            primecircle[num]=i;//将这个数字放入数组下一个位置 
            dfs(i);//对i深搜 
            vis[i]=0;//下一个初始化为未访问过 
            num--;//同一层的所以num减1与上一个保持一致
        }
    }
}

int main()
{
    int icase=0;
    while(cin>>n)
    {
        icase++;
        memset(vis, 0, sizeof(vis));
        memset(primecircle, 0, sizeof(primecircle));
        //规定第一个数为1 
        primecircle[1] = 1;
        num=1;
        vis[1]=1;
        cout<<"Case "<":"<1);
        cout<return 0;
}

你可能感兴趣的:(搜索,ACM)