码迷,mamicode.com
首页 > 编程语言 > 详细

题目1459:Prime ring problem(素数环问题——递归算法)

时间:2017-04-23 16:49:32      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:clu   素数   ++   class   printf   case   check   cep   ace   

题目链接:http://ac.jobdu.com/problem.php?pid=1459

详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus

参考代码:

//
//  1459 Prime ring problem.cpp
//  Jobdu
//
//  Created by PengFei_Zheng on 23/04/2017.
//  Copyright © 2017 PengFei_Zheng. All rights reserved.
//
 
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
#define PRIME 13
#define MAX_SIZE 21
using namespace std;
 
int n;
int ans[MAX_SIZE];
bool used[MAX_SIZE];
 
int prime[]={2,3,5,7,11,13,17,19,23,29,31,37,41};
bool judge(int x){
    for(int i = 0 ; i < PRIME ; i++){
        if(prime[i]==x)
            return true;
    }
    return false;
}
 
void check(){
    if(!judge(ans[n]+ans[1])) return;
    for(int i = 1 ; i <= n ; i++){
        if(i!=1) printf(" ");
        printf("%d",ans[i]);
    }
    printf("\n");
}
 
void DFS(int num){
    if(num>1){
        if(!judge(ans[num] + ans[num - 1])) return;
    }
    if(num==n){
        check();
        return;
    }
    for(int i = 2 ; i <= n ; i++){
        if(!used[i]){
            used[i] = true;
            ans[num+1] = i;
            DFS(num+1);
            used[i] = false;
        }
    }
}
 
int main(){
    int kase = 0;
    while(scanf("%d",&n)!=EOF){
        kase++;
        memset(used,false,sizeof(used));
        ans[1] = 1;
        used[1]=true;
        printf("Case %d:\n",kase);
        DFS(1);
        printf("\n");
    }
    return 0;
}
/**************************************************************
    Problem: 1459
    User: zpfbuaa
    Language: C++
    Result: Accepted
    Time:590 ms
    Memory:1520 kb
****************************************************************/

 

题目1459:Prime ring problem(素数环问题——递归算法)

标签:clu   素数   ++   class   printf   case   check   cep   ace   

原文地址:http://www.cnblogs.com/zpfbuaa/p/6752701.html

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