用了dfs非递归,略感复杂,用时居然400多MS,悲催。 #include<iostream> #include<stdio.h> #include<math.h> using namespace std; #define MAX 21 int mark[MAX]; int judge[MAX][MAX]; int stack[1000]; int n; bool prime(int x) { if(x==2||x==3 ||x==5||x==7||x==11||x==13||x==17||x==19 ||x==23||x==29 ||x==31 || x==37) return true; else return false; } void setjudge() { int i,j; int sum; for(i=1;i<20;i++) for(j=i+1;j<=20;j++) { sum=i+j; if(prime(sum)) { judge[i][j]=1; judge[j][i]=1; } } } void dfs() { int top=-1; int cur,i,pos=1,j; int flag; stack[++top]=1; mark[1]=1; while(top>-1) { flag=0; cur=stack[top]; while(!flag) { flag=1; for(i=pos+1;i<=n;i++) { if(!mark[i] && judge[cur][i]) { flag=0; mark[i]=1; stack[++top]=i; cur=i; pos=1; break; } } } if(top==n-1 && judge[stack[top]][1]) { for(j=0;j<n-1;j++) printf("%d ",stack[j]); printf("%d/n",stack[j]); } pos=stack[top]; mark[pos]=0; top--; } } int main() { int t=1; setjudge(); while(cin>>n) { cout<<"Case "<<t++<<":"<<endl; if(n%2==0) dfs(); cout<<endl; } return 0; }