Test instructions: gives N, the sequence from 1 to N, which outputs two adjacent numbers and a number of primes.
According to the Purple book, it is probably the place to note that when initializing the a[0]=1, then DFS (1), starting from the 1th position to search
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <cmath>5#include <stack>6#include <vector>7#include <map>8#include <queue>9#include <algorithm>Ten #definemod=1e9+7; One using namespacestd; A -typedefLong LongLL; - inta[1005],vis[1005],isp[1005]; the intN; - - voidIs_prime () { -isp[1]=isp[0]=1; + for(intI=2; i<=1005; i++){ - if(isp[i]==0){ + for(intj=i*2; j<=1005; j+=i) Aisp[j]=1; at } - } - } - - voidDfsintcur) { - inti; in if(cur==n&&!isp[a[0]+a[n-1]]){ - for(i=0; i<n-1; i++) printf ("%d", A[i]); toprintf"%d\n", A[i]); + } - the Else for(i=2; i<=n;i++) * if(!vis[i]&&!isp[i+a[cur-1]]){ $a[cur]=i;Panax Notoginsengvis[i]=1; -DFS (cur+1); thevis[i]=0; + } A } the + intMain () { - intt=0; $ is_prime (); $ while(cin>>N) { -memset (Vis,0,sizeof(Vis)); -a[0] =1; thevis[1] =1; - if(t) printf ("\ n");Wuyiprintf"Case %d:\n", ++t); theDfs1); - } Wu return 0; -}
View Code
Write your own time, is directly DFS (0), nothing can not be lost, but why is it so? = = The first topic of learning backtracking = = a good understanding again
UVa 524 Prime Ring problem "backtracking"