Prime Ring Problem(HDU1016)

Prime Ring Problem

思路:先看成一条链,往里头填数,满足任意相邻两数和为质数(这可以打表预处理出40以内的所有质数,扩展的时候枚举),填完了后检查首尾是否满足条件。字典序可以采用扩展时从小到大枚举。另外注意对于每个case多输出一个换行,行末不要有空格。

#include<bits/stdc++.h>
using namespace std;
int n,cnt,a[25];
bool p[45],vis[25];
void print()
{
    for(int i=1;i<=n;++i)
        printf("%d%c",a[i],i==n?'\n':' ');
}
void dfs(int step)
{
    if(step==n+1)
    {
        if(p[a[1]+a[n]])print();
        return;
    }
    for(int i=2;i<=n;++i)
    {
        if(vis[i])continue;
        if(p[a[step-1]+i])
        {
            vis[i]=true;
            a[step]=i;
            dfs(step+1);
            vis[i]=false;
        }
    }
}
int main()
{
    p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[19]=p[23]=p[29]=p[31]=p[37]=true;
    a[1]=1;vis[1]=true;
    while(scanf("%d",&n)!=EOF)
    {
        printf("Case %d:\n",++cnt);
        dfs(2);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zzctommy/p/12349921.html