码迷,mamicode.com
首页 > 其他好文 > 详细

UVA - 524 Prime Ring Problem(dfs回溯法)

时间:2015-07-27 20:42:14      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

 

 

                  UVA - 524 Prime Ring Problem

Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu

Description

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 技术分享 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 <= 16)

 

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.

 


You are to write a program that completes above process.

 

Sample Input 

6
8

 

Sample Output 

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

 紫书194页原题

题解:输入正整数n,把1—n组成一个环,是相邻的两个整数为素数。输出时从整数1开始,逆时针排列。同一个环恰好输出一次,n (0 < n <= 16)

暴力解决会超时,应用回溯法,深度优先搜索

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int n;
int a[20],vis[20];

int isp(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&&isp(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]&&isp(i+a[s]))   //如果i没有用过,并且与钱一个数之和为素数
            {
                a[s+1]=i;
                vis[i]=1;              //标记
                dfs(s+1);
                vis[i]=0;              //清除标记
            }
        }
    }
}
int main()
{
    int t=0;
    while(cin>>n)
    {
        memset(vis,0,sizeof(vis));
        a[1]=1;
        if(t!=0) cout<<endl;            //一定注意输出格式
        t++;
        cout<<"Case "<<t<<":"<<endl;
        dfs(1);
    }
    return 0;
}

 

UVA - 524 Prime Ring Problem(dfs回溯法)

标签:

原文地址:http://www.cnblogs.com/hfc-xx/p/4680972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!