HDU - 1016 - Prime Ring Problem(全排列)
题目链接:https://vjudge.net/problem/HDU-1016
题目大意:让你构造一个n个数组成的环,每两个相邻的数之合都是素数
只要用递归算出来所有符合条件的全排列即可
#include<set> #include<map> #include<stack> #include<queue> #include<cmath> #include<cstdio> #include<cctype> #include<string> #include<vector> #include<climits> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define endl '\n' #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) #define mst0(a) memset(a, 0, sizeof(a)) #define mstnil(a) memset(a, -1, sizeof(a)) #define mstinf(a) memset(a, 0x3f3f3f3f, sizeof(a)) #define IOS ios::sync_with_stdio(false) #define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n") using namespace std; typedef long long ll; typedef pair<int, int> P; const double pi = acos(-1.0); const double eps = 1e-7; const ll MOD = 1e9+7; const int INF = 0x3f3f3f3f; const int NIL = -1; template<typename T> ll read(T &x){ x = 0; char ch = getchar(); ll fac = 1; while(!isdigit(ch)) { if(ch == '-') fac*=-1; ch = getchar(); } while(isdigit(ch)) { x = x*10+ch-48; ch = getchar(); } x*=fac; return x; } const int maxn = 1e3+10; int prime[maxn], kase, nums[maxn], vis[maxn]; bool isprime[maxn] = {1, 1}; void primeMaker() { for (int i = 2; i<maxn; ++i) { if (!isprime[i]) prime[kase++] = i; for (int j = 0; j<kase && i*prime[j] < maxn; ++j) { isprime[prime[j]*i] = true; if (!(i%prime[j])) break; } } } void dfs(int pos, int n) { if (pos > n && !isprime[nums[1]+nums[n]]) for (int i = 1; i<=n; ++i) printf(i == n ? "%d\n" : "%d ", nums[i]); else if (pos > n) return; else { for (int i = 2; i<=n; ++i) if (!vis[i] && !isprime[i+nums[pos-1]]) { nums[pos] = i; vis[i] = true; dfs(pos+1, n); vis[i] = false; } } } int main(void) { int n, ccase = 1; primeMaker(); while(~scanf("%d", &n)) { printf("Case %d:\n", ccase++); mst0(vis); nums[1] = 1; vis[1] = true; dfs(2, n); putchar(endl); } return 0; }