欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

L - 12 C++

程序员文章站 2022-07-14 08:37:41
...

题目:

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. 

L - 12 C++ 
Inputn (0 < n < 20). 
OutputThe 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

思路:

DFS。输出要空一行,每行最后没有空格。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n;
int vis[30];
int tot[30];
int ans;
int prime(int a)
{
    int flag=0;
    for(int i=2;i<=sqrt(a)+1;i++)
    {
        if(a%i==0)flag=1;
    }
    if(flag==1)return 0;
    else return 1;
}
void dfs(int num,int ans)
{
    tot[ans]=num;
    vis[num]=1;
    int i;
    if(ans==n-1&&prime(tot[ans]+tot[0])==1)
    {
        cout<<tot[0];
        for(i=1;i<n;i++)
        {
            cout<<" "<<tot[i];
        }
        cout<<endl;
    }
    for(i=2;i<=n;i++)
    {
        if(prime(i+num)==1&&vis[i]==0)
        {
            vis[i]=1;
            dfs(i,ans+1);
            vis[i]=0;
        }
    }
}
int main()
{
    int t=0;
    while(scanf("%d",&n)!=EOF)
    {
        t++;
        printf("Case %d:\n",t);
        ans=0;
        dfs(1,0);
        cout<<endl;
    }
    return 0;
}