http://tjuacm.chaosheng.top/problem.php?id=1265
https://vjudge.net/problem/HDU-1016
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N = 30; int n; int path[N]; bool visit[N]; bool isPrime(int x){ for(int i = 2; i * i <= x; i++){ if(x % i == 0) return false; } return true; } void dfs(int pos){ if(pos == n && isPrime(path[n-1] + 1)){ for(int i = 0; i < n-1; i++){ printf("%d ", path[i]); } printf("%d\n", path[n-1]); } if(pos == n) return ; for(int i = 2; i <= n; i++){ if(!visit[i] && isPrime(path[pos-1] + i)){ path[pos] = i; visit[i] = 1; dfs(pos + 1); visit[i] = 0; } } } int main(){ int t = 0; while(cin >> n){ t++; memset(visit, 0, sizeof(visit)); path[0] = 1; visit[1] = 1; printf("Case %d:\n", t); dfs(1); printf("\n"); } return 0; }