https://github.com/hustcc/canvas-nest.js

zoj 1457 Prime Ring Problem

#include <stdio.h>
#include <math.h>
#include <string.h>

int num[21],n,ans[21];
bool vis[21];
bool Check(int num){
	for(int i=2;i<=sqrt(num);i++)
		if(num%i==0)
			return false;
	return true;
}

void DFS(int t){
	if(t==n){
		if(!Check(ans[n-1]+1))
			return ;
		for(int i=0;i<n-1;i++)
			printf("%d ",ans[i]);
		printf("%d\n",ans[n-1]);
		return ;
	}
	for(int i=2;i<=n;i++)	
		if(vis[i]==false&&Check(ans[t-1]+i)){
			ans[t]=i;	
			vis[i]=true;
			DFS(t+1);
			vis[i]=false;
		}
}

int main(){
	
	int t=0;
	while(scanf("%d",&n)==1){
		for(int i=1;i<=n;i++)
			num[i]=i;
		memset(vis,false,sizeof(vis));
		ans[0]=1,vis[0]=true;
		printf("Case %d:\n",++t);
		if(n%2==1){
			puts("");
			continue;
		}
		else
			DFS(1);
	    puts("");
	}
	return 0;
} 
posted @ 2016-01-29 13:14  坏小孩不坏  阅读(137)  评论(0编辑  收藏  举报