标签:uva
题意:
把编号为1到n的珠子,串成手环,要求任意两个相邻的珠子和都为质数;
思路:
数据量只有16,打个质数表,直接dfs搜就行了;
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int vis[32]; int viss[20]; int res[20],n; void init() { vis[1] = 1; for(int i = 2; i <= 31;i++) { if(!vis[i]) { for(int j = i + i; j <= 31; j += i) vis[j] = 1; } } return; } void dfs(int pre,int sum) { if(sum == n) { if(!vis[pre + 1]) { printf("%d",res[1]); for(int i = 2; i <= n;i++) { printf(" %d",res[i]); } printf("\n"); } return; } for(int i = 1; i <= n; i++) { if(!viss[i] && !vis[i + pre]) { viss[i] = 1; res[sum + 1] = i; dfs(i,sum + 1); viss[i] = 0; } } return; } int main() { int cas = 1; init(); bool f = 0; while(scanf("%d",&n) == 1) { if(f) printf("\n"); else f = 1; memset(viss, 0,sizeof(viss)); printf("Case %d:\n",cas++); viss[1] = 1; res[1] = 1; dfs(1,1); } }
标签:uva
原文地址:http://blog.csdn.net/yeyeyeguoguo/article/details/45312207