I use DFS for this question. Don't say much, look at the code and comments.
#include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <vector >using namespace Std;
Because of the n<20, so the largest prime is about 40, so use an array to record the number of primes within 45 for subsequent judgments. BOOL isprime[45]={0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,1,0}; The int n;bool visited[24];//is used to mark whether the void Dfs (int cnt,int id,int ans[]) {if (cnt==n+1) {printf ("%d", ans[1]) has been accessed; for (int i=2;i<=n;i++) printf ("%d", ans[i]); printf ("\ n"); Return } for (int i=2;i<=n;i++) {if (visited[i]| | I==id) continue; Visited[i]=true; if (cnt==n)//Here note to distinguish whether to reach the nth number, if the arrival because it is a ring, so also to determine and 1 is not a prime. {int t1=ans[cnt-1]+i; int t2=i+1; if (Isprime[t1]&&isprime[t2]) {ans[cnt]=i; DFS (Cnt+1,i,ans); }} else//Otherwise, the sum of the previous number is not the primes {int t=ans[cnt-1]+i; if (Isprime[t]) {ans[cnt]=i; DFS (Cnt+1,i,ans); }} visited[i]=false;//remember to restore}}int maiN () {int k=1; while (scanf ("%d", &n)!=eof) {int ans[25]; Ans[1]=1; memset (visited,false,sizeof (visited)); Visited[1]=true; printf ("Case%d:\n", k++); DFS (2,1,ans); printf ("\ n"); } return 0;}
HDU 1016 Prime Ring problem