1016

/*Description: to 
 * 
 * Author: Vincent
 * 
 * Date:2010/04/
 * Contact:agilely@126.com 
 * Zju CS Lab
 */
//给定长度 输出相邻和为素数的圈
//查找方法为难点
#include <stdio.h>    //给定小范围内素数可以用枚举解决,快很多
#include <math.h>
int sushu(int a);
int place(int x[],int k);
int prime[12]={2,3,5,7,11,13,17,19,23,29,31,37}; 
int place(int x[],int k)
{	//k是否满足题意,是否可加入x[]
    int i;
    for(i=1;i<k;i++)
        if(x[i]==x[k]||(sushu(x[k]+x[k-1])==0))
            return 0;//一旦有重复||与前一个和不为素数
    return 1;
}
int sushu(int a)
{ //判断给定的数是不是素数  小范围查表
    int i;
    for(i=0;i<=11;i++)
    {
        if(a==prime[i])
        {
            return 1;
        }
    }
    return 0;
}
int a[200000][50],n;
int x[100000];
int main()
{
    
    int i,j,k,d,s,c=0;
    
    while(scanf("%d",&n)!=EOF)
    {	//输入数列长度
        k=1;
        x[1]=0;
        s=1;//找到的数列组数
        
        while(k>0)//搜索部分
        {
            x[k]=x[k]+1;
            while(x[k]<=n&&(!place(x,k)))
            {//用k扫描满足题意的存入x[]
                x[k]=x[k]+1;
            }
            if(x[k]<=n)
            {
                if(k==n)
                {
                    if(x[1]!=1)
                            break;
                    if(sushu(x[n]+x[1])==1)//最后一步:若首尾和为素数
                    {	//a[i][j] a[i]放找到的数列

                        for(d=1;d<=n;d++)
                        {
                            a[s][d]=x[d];
                        }//s为找到的组数
                        s++;
                    }
                }else
                {
                    k=k+1;x[k]=0;
                }
            }else
            {
                x[k]=0;k=k-1;
            }        
        }
        printf("Case %d:\n",++c);
        for(i=1;i<s;i++)
        {

            for(j=1;j<=n;j++)
            {
              if(j==1)
              {
                printf("%d",a[i][j]);
              }else
              {
                  printf(" %d",a[i][j]);
              }
            }
            printf("\n");  
        }
        printf("\n");  
    }
}


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
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
posted @ 2010-04-15 22:59  にんじゃ  阅读(110)  评论(0)    收藏  举报