G - Prime Ring Problem

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

题意概括  :

给你一个数据n,从1到n的数组成素数环,要求相邻的两个数相加为素数.

解题思路  :

搜索,从1开始,首先判断和一相加能组成素数的,把他们存到数组中,以此类推,当放置的数的个数等于k的时候,直接输出数组.

#include<stdio.h>
#include<string.h>
#include<math.h>

int book[30],a[30];
int k;
int prime(int m)
{
    int i,h;
    if(m == 1)
    return 0;
    h = (int)sqrt(m);
    
    for(i = 2;i<=h;i ++)
    {
        if(m % i == 0)
        return 0;
    }
    return 1;
}
int dfs(int n)
{
    int i,j;
    if(n ==k+1&&prime(a[1]+a[k]))
    {
        for(j = 1;j < k;j ++)
        printf("%d ",a[j]);
        printf("%d\n",a[k]);
    }
    else
    {
        for(i = 2;i <= k;i ++)
        {
            if(prime(a[n-1]+i) && book[i]==0)
            {
                book[i] = 1;
                a[n] = i;
                dfs(n+1);
                book[i] = 0;
            }
        }
    }
}
int main()
{
    int i,b;
    b = 0;
    while(~ scanf("%d",&k))
    {
        memset(a,0,sizeof(a));
        memset(book,0,sizeof(book));
        b ++;
        a[1] = 1;
        book[1] = 1;
        printf("Case %d:\n",b);
        dfs(2);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/y1356998843/article/details/81094493