hdu1016

来源:互联网 发布:卧蚕阿姨的淘宝店 编辑:程序博客网 时间:2024/05/21 00:17
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
68
 

Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
 



一道简单的DFS递归


检查一个数是否为素数时,可以建立一个数组  但是要注意n的范围是<20 所以这个数组的大小最小应该是40 而不是20! 我就犯了这个毛病开始WA了半天。


代码如下:


#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<stdio.h>
#include<cmath>
#include<vector>
#include<list>
using namespace std;
bool Prime[41] = {0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,
                    1,0,0,0,0,0,1,0,0,0};
int Visited[21];
int t[21];
int n;
void DFS(int k)
{
    if(k == n)
    {
        int i;
        for( i = 0;i < n-1;i++)
        {
            cout<<t[i]<<" ";
        }
        cout<<t[n-1]<<endl;
        return;
    }
    for(int j = 2;j <= n;j++)
    {
        if(Visited[j] != 1&&Prime[t[k-1]+j])
        {
        
               if((k == n-1) && (!Prime[1+j]))
               continue;
               t[k] = j;
               Visited[j] = 1;
               DFS(k+1);
               Visited[j] = 0;
        }
    }
}
int main()
{
    int i,j;
    j = 1;
    while(~scanf("%d",&n))
    {
        memset(Visited,0,sizeof(Visited));
        t[0] = 1;
        cout<<"Case "<<j<<":"<<endl;
        j++;
        DFS(1);
        cout<<endl;
    }
    return 0;
}




0 0
原创粉丝点击