HDU 1016 Prime Ring Problem

来源:互联网 发布:开淘宝店的准备工作 编辑:程序博客网 时间:2024/06/04 00:26
Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 49304    Accepted Submission(s): 21745


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
 
     本题题意:
          给你n个数让你用从1—n的n个数围成一个环,使相邻两个数之和为素数。
  解题思路:
  用回溯法搜索,深度优先搜索。
  难过注意:
 注意题目的输出格式,因为格式错误WA了好几遍呢!!!

   代码:
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>#include <queue>using namespace std;int n;int a[25],vis[25];bool sushu(int n)///判断素数{    if(n<2)        return false;    for(int i=2; i*i<=n; i++)    {        if(n%i==0)            return false;    }    return true;}void dfs(int s){    if(s==n&&sushu(a[1]+a[n]))///边界条件    {        for(int i=1; i<n; i++)        {            cout<<a[i]<<" ";        }         cout<<a[n]<<endl;    }    else    {        for(int i=2; i<=n; i++)        {            if(!vis[i]&&sushu(i+a[s]))///如果i未被用过,并与前一个数之和为素数            {                a[s+1]=i;                vis[i]=1;///标记                dfs(s+1);///深搜                vis[i]=0;///重置标记数组            }        }    }}int main(){    int t=0;///记录情况数    while(scanf("%d",&n)!=EOF)    {        memset(vis,0,sizeof(vis));        a[1]=1;        t++;        cout<<"Case "<<t<<":"<<endl;        dfs(1);        cout<<endl;///每种情况下打印一行空白行    }    return 0;}

3 0
原创粉丝点击