Prime Ring Problem
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016
简单的素数环问题,只需不断向后推进
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<cmath>
using namespace std;
int prime[13]={ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41};
int pre[24] = {1};
int cnt=0;
int isPrime(int x);
int isUsed(int x, int len);
void find( int lastInt, int sum ){
if( sum==cnt && isPrime( lastInt +1 ) ) {
for(int i=0; i<sum-1; i++)
printf("%d ", pre[i]);
printf("%d\n", pre[sum-1]);
return ;
}
// 每次递归向后推进
for( int i=2; i<=cnt; i++){
if( !isUsed( i, sum ) && isPrime( i + lastInt)){
pre[sum] = i;
find( i, sum+1);
}
}
}
//判断是否为素数
int isPrime(int x){
int res = 0;
for(int i=0; i<13; i++)
if( prime[i]==x ) {res=1; break;}
return res;
}
//判断是否使用过
int isUsed(int x, int len){
int res = 0;
for(int i=0; i<len; i++)
if( pre[i]==x ) {res=1; break;}
return res;
}
int main(){
int num=0;
while( scanf("%d", &cnt)==1 ){
printf("Case %d:\n", ++num);
find( 1, 1);
printf("\n");
}
return 0;
}