HDU 1016 Prime Ring Problem

来源:互联网 发布:p2p网络借贷入罪 编辑:程序博客网 时间:2024/06/10 07:26

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1016


暴力DFS,无剪枝,如判素数优化。

#include<iostream>#include<cmath>using namespace std;int N;int num[25];bool judge(int n){    int mark=1;    double temp=sqrt((double)n);    for(int i=2;i<=temp;i++)    {        if(n%i==0)        {            mark=0;            break;        }    }    if(mark)        return true;    else        return false;}void DFS(int n){    int i,j;    if(n>N)    {        for(i=1;i<N;i++)            cout<<num[i]<<" ";        cout<<num[N]<<endl;    }    else    {        for(i=1;i<=N;i++)        {            int ok=1;            num[n]=i;            for(j=1;j<n;j++)            {                if(n!=N)                {                    if(!judge(num[n]+num[n-1])||num[n]==num[j])                    {                        ok=0;                        break;                    }                }                else                {                    if(!judge(num[n]+num[n-1])||num[n]==num[j]||!judge(num[n]+num[1]))                    {                        ok=0;                        break;                    }                }            }            if(ok)                DFS(n+1);        }    }}int main(){    int T=1;    while(cin>>N)    {        cout<<"Case "<<T<<":"<<endl;        num[1]=1;        DFS(2);        T++;        cout<<endl;    }    return 0;}

0 0
原创粉丝点击