首页 > 代码库 > hdu-1016 Prime Ring Problem

hdu-1016 Prime Ring Problem

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

经典 dfs问题:没有剪枝  218ms

#include<cstdio>
#include<cstring>
int n,vis[21],a[21];
bool is_prime(int x)
{
    if(x==2||x==3) return 1;
    if(x==1) return 0;
    for(int i=2;i*i<=x;i++)
        if(x%i==0) return 0;
    return 1;
}
void dfs(int x)
{
    if(x==n&&is_prime(a[n]+a[1]))
    {
        for(int i=1;i<=n;i++)
        {
            if(i!=n) printf("%d ",a[i]);
            else printf("%d\n",a[i]);
        }
        return;
    }
    for(int i=2;i<=n;i++)
    {
        if(!vis[i]&&is_prime(a[x]+i))
        {
            vis[i]=1;
            a[x+1]=i;
            dfs(x+1);
            vis[i]=0;
        }
    }
}

int main()
{
    int i=1;
    while(scanf("%d",&n)!=EOF)
    {
        printf("Case %d:\n",i++);
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
        a[1]=1;
        vis[1]=1;
        dfs(1);
        printf("\n");
    }
    return 0;
}


 

hdu-1016 Prime Ring Problem