hdu1016
产生一个素数换
DFS
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 DFS, 形成素数环 3 */ 4 #include<stdio.h> 5 #include<stdlib.h> 6 #include<string.h> 7 #define maxn 24 8 int num[ maxn ],vis[ maxn ]; 9 bool prime( int a ){ 10 for( int i=2;i<=(a+1)/2;i++ ){ 11 if( a%i==0 ) return false; 12 } 13 return true; 14 } 15 void dfs( int num_index,int vis_index ,int n ){ 16 vis[ vis_index ]=1; 17 num[ num_index ]=vis_index; 18 if( num_index==n && prime(num[1]+num[n])==true ) { 19 for( int i=1;i<=n;i++ ){ 20 if( i==1 )printf("%d",num[i]); 21 else printf(" %d",num[i]); 22 } 23 printf("\n"); 24 return ; 25 } 26 for( int i=2;i<=n;i++ ){ 27 if( vis[i]==1 )continue; 28 if( prime( num[ num_index ]+i ) == false )continue; 29 dfs( num_index+1,i,n ); 30 vis[ i ]=0; 31 } 32 } 33 34 int main(){ 35 int n; 36 int ca=1; 37 while( scanf("%d",&n) ==1 ){ 38 printf("Case %d:\n",ca++); 39 memset( vis,0,sizeof(vis) ); 40 dfs(1,1,n); 41 printf("\n"); 42 } 43 return 0; 44 }
keep moving...