首页 > 代码库 > UVA - 524 Prime Ring Problem(素数环)(回溯法)
UVA - 524 Prime Ring Problem(素数环)(回溯法)
题意:输入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; }
UVA - 524 Prime Ring Problem(素数环)(回溯法)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。