HDU 1016 Prime Ring Problem DFS + 记忆化搜索
2011-05-04 20:04
387 查看
说实话,这题真没做出来,思路有,但是有问题一直不能解决,后来别人提供的思路.
不多说了....
这题就是要求形成一个环,没两个相邻的数之和不能为素数,当然最后一个要考虑他跟第一个的关系,这里的DFS其实只要递归一个东西,而我递归的东西却一直不对,主要受变形课影响,其实递归的东西肯定是当前的数目,然后把当前的数存在数组里,以便下一次递归的时候可以跟这一次的数比较....
不多说了....
这题就是要求形成一个环,没两个相邻的数之和不能为素数,当然最后一个要考虑他跟第一个的关系,这里的DFS其实只要递归一个东西,而我递归的东西却一直不对,主要受变形课影响,其实递归的东西肯定是当前的数目,然后把当前的数存在数组里,以便下一次递归的时候可以跟这一次的数比较....
#include<stdio.h> #include<string.h> int n,num[25],des[25]; int gcd( int n ) { int f = 0; if( n == 2 || n == 3 ) return 1; for( int i = 2; i <= n / 2; ++i ) if( n % i == 0 ) return 0; return 1; } void DFS( int x ) { if( x == n && gcd( num + 1 ) )//当到最后一个时 { for( int i = 1; i <= n; ++i ) printf( i == 1 ? "%d": " %d",num[i] );//满足条件则直接输出来 puts( "" ); } else { for( int i = 2; i <= n; ++i ) { if( !des[i] && gcd( i + num[x] ) )//查找满足条件的数 { des[i] = 1;//记忆 num[x+1] = i; DFS( x + 1 ); des[i] = 0;//回溯 } } } } int main( ) { int t = 0; while( scanf( "%d",&n ) != EOF ) { memset( num,0,sizeof( num ) ); memset( des,0,sizeof( des ) ); des[1] = num[1] = 1; printf( "Case %d:\n",++t ); DFS( 1 ); puts( "" ); } return 0; }
相关文章推荐
- 搜索专题(DFS)HDU 1016-Prime Ring Problem
- HDU 1016 Prime Ring Problem(搜索入门题 DFS,多种方式)
- HDU 1016-Prime Ring Problem(DFS)
- HDU 1016 Prime Ring Problem (DFS)
- HDU 1016 Prime Ring Problem(DFS)
- [ACM] hdu 1016 Prime Ring Problem (DFS)
- HDU 1016 Prime Ring Problem (DFS回溯)
- HDU 1016 Prime Ring Problem(DFS 素数环问题)
- hdu-1016 Prime Ring Problem(素数环 dfs)
- HDU 1016 Prime Ring Problem(DFS回溯+素数判断)
- hdu 1016 Prime Ring Problem(DFS)
- HDU 1016(Prime Ring Problem)DFS
- [ACM] hdu 1016 Prime Ring Problem (DFS)
- HDU 1016 Prime Ring Problem(DFS)
- hdu 1016 Prime Ring Problem (DFS)
- HDU-1016 Prime Ring Problem (DFS)
- HDU 1016 Prime Ring Problem 简单DFS
- HDU 1016 Prime Ring Problem DFS
- HDU(1016)搜索Prime Ring Problem
- HDU 1016 Prime Ring Problem DFS