码迷,mamicode.com
首页 > 其他好文 > 详细

Prime Ring Problem

时间:2015-03-20 01:18:14      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30395    Accepted Submission(s): 13525


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
 
//第一次写dfs,既然发现和小白上的代码一样,开心
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int prime[]= {0,0,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 flag[25];//标志数组
int c[25];//结果数组
int n;
void dfs(int cur)
{
    int i,j;
    if(cur==n+1&&prime[1+c[cur-1]])//别忘记第一个数和最后一个数的和也应该是素数
    {
        for(j=1; j<n; j++) printf("%d ",c[j]);
        printf("%d\n",c[n]);
    }
    else for(i=2; i<=n; i++)//每个数都应是从2——n选择
            if(!flag[i]&&prime[i+c[cur-1]])//是否满足条件
            {
                c[cur]=i;//尝试把i作为第cur个满足条件的数
                flag[i]=1;//设置使用标志
                dfs(cur+1);
                flag[i]=0;//谨记清除标记
            }
}
int main()
{
    int k=1;
    while(~scanf("%d",&n))
    {
        printf("Case %d:\n",k++);
        memset(flag,0,sizeof(flag));
        c[1]=1;
        dfs(2);//第一个数就是1,从第二个数开始
        printf("\n");
    }
}
不知什么鬼,G++提交超时,c++ 256ms

Prime Ring Problem

标签:

原文地址:http://www.cnblogs.com/orchidzjl/p/4352305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!