No Answer
这道题太坑了,用回溯法提交多次总是时间超限,最后看了别人的才知道奇数除了1可以,其他都不可以。
#include<iostream> #include<cstring> using namespace std; int A[25],vis[25]; int n; bool isp[]= {0, 0, 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}; void dfs(int cur) { if(cur==n&&isp[A[0]+A[n-1]]) { for(int i=0; i<n; i++) cout<<A[i]<<" "; cout<<endl; return; } else for(int i=2; i<=n; i++) { if(!vis[i]&&isp[i+A[cur-1]]) { A[cur]=i; vis[i]=1; dfs(cur+1); vis[i]=0; } } } int main() { int k=1,i; while(cin>>n&&n) { cout<<"Case "<<k++<<":"<<endl; memset(vis,0,sizeof(vis)); A[0]=1; if ( n % 2 == 0 && n != 1 ) { dfs(1); } else if ( n == 1 ) { cout << "1" << endl; } else cout << "No Answer" << endl; } }