SDAU 搜索专题 20 Prime Ring Problem

来源:互联网 发布:图灵机思想 知乎 编辑:程序博客网 时间:2024/06/07 04:48

1:问题描述
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

2:大致题意
这里写图片描述
构造一个素数环,让相邻数的和为素数。

3:思路

这个题要用到DFS,思路挺简单的。因为只有20个数,所以可以打一个素数表。一个数一个数的检索,如果它没有用过并且和相邻的的数的和为素数就放进去。一次一次的递归就好啦~~

4:感想

我觉得DFS的题思路很简单,但是程序不怎么好写,可能是我递归不怎么熟练。参加了一个比赛,只做出了1个题。〒_〒,欸~~

5:ac代码

#include<iostream>#include<cstdio>#include<stdio.h>#include<cstring>#include<cmath>using namespace std;int prime[40]={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};int n,cou;int num[25];       //可选数。int vis [25];     //标记是否用过。int cc[25];       //素数环。void dfs(int now){    int i;    if(now==n&&prime[1+cc[n]])    {        for(i=1;i<=n;i++)        {            if(i==1)                cout<<cc[i];            else                cout<<" "<<cc[i];        }        cout<<endl;    }    else    {        for(i=2;i<=n;i++)        {            if(prime[i+cc[now]]&&!vis[i])   //和为素数并且没有用过。            {                vis[i]=1;                now++;                cc[now]=i;               //cout<<cc[now]<<"  "<<cc[now-1]<<endl;                dfs(now);                now--;     //恢复现场!很重要的一步。                vis[i]=0;            }        }    }}int main(){    //freopen("r.txt","r",stdin);    int i,j;    cou=1;    while(cin>>n)    {        cout<<"Case "<<cou<<":"<<endl;        num[1]=cc[1]=1;        for(i=2;i<=n;i++)            num[i]=i;        memset(vis,0,sizeof(vis));        vis[1]=1;        dfs(1);        cou++;        if(cou!=1)            cout<<endl;    }}
0 0
原创粉丝点击