杭电 HOJ 1016 Prime Ring Problem 解题报告
素数环,回溯法,DFS基础题。对于DFS偶还没接触过,看到一篇好的文章,分享下:http://yangjunke111.blog.163.com/blog/static/135279606201041312753102/
额,直接看代码吧
#include <iostream> using namespace std; int n,cas=1,visit[20],result[20]={0,1},p[]={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,0,1,0}; void DFS(int num,int pos) { int i; if(pos==n&&p[1+result[n]]) { printf("1"); for(i=2;i<=n;i++) printf(" %d",result[i]); printf("\n"); return; } for(i=2;i<=n;i++) if(p[i+num]&&!visit[i]) { result[pos+1]=i; visit[i]=1; DFS(i,pos+1); visit[i]=0; } } int main() { while(cin>>n) { memset(visit,0,sizeof(visit)); printf("Case %d:\n",cas++); if(n%2==0) DFS(1,1); printf("\n"); } }