A - Prime Ring Problem
#include<iostream> #include<cmath> #include<cstring> using namespace std; int n; int a[100]; int vis[100]; int num; int prime(int c){ for(int m=2;m<=sqrt(c);m++){ if(c%m==0) return 0; } return 1; } void dfs(int i){ int he; int flag; if(i==n&&prime(a[0]+a[n-1])){ for(int m=0;m<n;m++){ if(m<n-1) cout<<a[m]<<" "; else cout<<a[m]; } cout<<endl; return; } for(int j=2;j<=n;j++){ he=a[i-1]+j; flag=prime(he); if(vis[j]==0&&flag){ vis[j]=1; a[i]=j; dfs(i+1); vis[j]=0; } } return; } int main(){ while(cin>>n){ cout<<"Case "<<++num<<":"<<endl; memset(a,0,sizeof(a)); memset(vis,0,sizeof(vis)); a[0]=1; dfs(1); cout<<endl; } }
Strict compliance with this problem Xu dfs template, solving the problem when planted in a critical condition when the judgment
If the incoming time to the initial value of i is 1, there will be determined when he prime numbers i-1, so a [1] the second number is stored, it is assumed that when we pass n is 6, when i = 6, if not enter if statement, a case has been subjected to i equals 12,345 searches, vis each array will be marked, and the array is a predetermined vis 2-6 total of five positions, at this time we have no more room, and has not enter the if statement, so in this case i is == critical condition, the idea is this, and also set up specific incoming initial value of i and j are related
There is the problem of the required output format, with a space between each of the two numbers, the last number with no spaces, and each group after the end of the case to a blank line, easy to overlook.