ZOJ 1457 Prime Ring Problem @Z

来源:互联网 发布:淘宝卖家互刷交流群 编辑:程序博客网 时间:2024/06/05 05:09

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1457

http://acm.hdu.edu.cn/showproblem.php?pid=1016


96年的上海。题意,1~N围成一圈,每相邻俩数和必须为质数,第一位必须是1,按字典序输出。水题,深搜,每一个位置判断一下与前一个和是否为质数。最后一位再判断与1之和是否为质数。显然,只有N为偶数时才有可能构造出来,N为奇数时则直接输出空行就好。没有这一句判断,HDOJ上可以过,ZOJTLE

#include<iostream>

#include<cstdio>

#include<set>

#include<cmath>

using namespace std;

int a[100],n;

set<int> b;

bool num[200];

void cir(int m,int l)

{

     int j;

     if (m==(n+1))

     {

        if (b.find(l+1)!=b.end())//ÕâÊÇÒ»¸ö»·£¬ËùÒÔÐèÒª¿¼ÂÇ×îºóÒ»¸öÔªËغ͵ÚÒ»¸öÔªËØÖ®ºÍ 

        {

           for (j=1;j<n;j++) cout<<a[j]<<' ';

           cout<<a[n]<<endl;

        }

     }

     else

     {

         for (j=2;j<=n;j++)

         if (num[j]==true)

         {

             int x=j+l;

             if (b.find(x)!=b.end())

             {

                num[j]=false;

                a[m]=j;

                cir(m+1,j);

                num[j]=true;

             }

         }

     }

}

int main()

{

    int i,k=0,j;

    

    bool f;

    b.insert(2);

    for (i=3;i<=37;i++)

    {

        f=true;

        for (j=2;j<=(sqrt(i)+1);j++)

        if (i%j==0) {f=false;break;}

        

        if (f==true) b.insert(i);

    }

    

    a[1]=1;

    num[1]=false;

    for (i=2;i<=19;i++) num[i]=true; 

    while (1)

    {

        if (scanf("%d",&n)==EOF) break;

        k++;

        printf("Case %d:\n",k);

        if (n%2!=0) {cout<<endl;continue;}

        

        cir(2,1);

        cout<<endl;

    }

    

    return 0;

}

原创粉丝点击