[2016-02-19][UVA][524][Prime Ring Problem]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[2016-02-19][UVA][524][Prime Ring Problem]相关的知识,希望对你有一定的参考价值。
[2016-02-19][UVA][524][Prime Ring Problem]
UVA - 524
Description A ring is composed of n (even number) circles as shown in diagram. Put natural numbers into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Inputn (0 < n <= 16)OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements.
Sample Input6 8 Sample OutputCase 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2 Miguel A. Revilla 1999-01-11 |
- 时间:2016-02-19 21:16:47 星期五
- 题目编号:UVA 524
- 题目大意:给定数字n,输出1~n的数字组成的排列,使得这些排列相邻的数字之和是素数(首位相连)
- 方法:dfs枚举答案,回溯优化.
- 解题过程遇到问题:
- 格式问题:最后一组数据后面没有空行,否则WA
- 每行最后一个数字后面没有空格,否则PE
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; typedef long long LL; #define CLR(x,y) memset((x),(y),sizeof((x))) #define FOR(x,y,z) for(int (x)=(y);(x)<(z);(x)++) #define FORD(x,y,z) for(int (x)=(y);(x)>=(z);(x)--) #define FOR2(x,y,z) for((x)=(y);(x)<(z);(x)++) #define FORD2(x,y,z) for((x)=(y);(x)>=(z);(x)--) const int maxn = 20; int ispri[maxn*2],n,vis[maxn],res[maxn]; void setpri(){ ispri[1] = 1; CLR(ispri,-1); FOR(i,2,maxn*2){ if(ispri[i]){ for(int j = i + i;j < maxn*2;j += i) ispri[j] = 0; } } } void dfs(int cur){ if(cur == n ){ if(!ispri[res[0] + res[n - 1]]) return ; printf("%d",res[0]); FOR(i,1,n){ printf(" %d",res[i]); } puts(""); return ; } FOR(i,2,n+1){ if(!vis[i] && ispri[ res[cur - 1] + i ]){ vis[i] = 1; res[cur] = i; dfs(cur + 1); vis[i] = 0; } } } int main(){ int cntcase = 0; setpri(); while(~scanf("%d",&n)){ if(cntcase) puts(""); printf("Case %d:\n",++cntcase); CLR(vis,0); vis[1] = res[0] = 1; dfs(1); } return 0; } |
!--WizRtf2Html>!--WizRtf2Html>
以上是关于[2016-02-19][UVA][524][Prime Ring Problem]的主要内容,如果未能解决你的问题,请参考以下文章