题意:输入n,把1~n组成个环,相邻两个数之和为素数。
分析:回溯法。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 100 + 10; const int MAXT = 10000 + 10; using namespace std; int prime[MAXN]; int a[MAXN]; int vis[MAXN]; int n; void init(){ for(int i = 2; i < MAXN; ++i) prime[i] = 1; for(int i = 2; i < MAXN; ++i){ if(prime[i]){ for(int j = i + i; j < MAXN; j += i){ prime[j] = 0; } } } } void dfs(int cur){ if(cur == n && prime[a[n] + a[1]]){ for(int i = 1; i <= n; ++i){ if(i != 1) printf(" "); printf("%d", a[i]); } printf("\n"); } else{ for(int i = 2; i <= n; ++i){ if(!vis[i] && prime[a[cur] + i]){ vis[i] = 1; a[cur + 1] = i; dfs(cur + 1); vis[i] = 0; } } } } int main(){ init(); a[1] = 1; int kase = 0; while(scanf("%d", &n) == 1){ if(kase) printf("\n"); printf("Case %d:\n", ++kase); dfs(1); } return 0; }
时间: 2024-12-22 15:22:54