首页 > 代码库 > HDU 1016 Prime Ring Problem (素数筛+DFS)
HDU 1016 Prime Ring Problem (素数筛+DFS)
题目链接
题意 : 就是把n个数安排在环上,要求每两个相邻的数之和一定是素数,第一个数一定是1。输出所有可能的排列。
思路 : 先打个素数表。然后循环去搜。。。。。
1 //1016 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 6 using namespace std ; 7 8 bool vis[21]; 9 int prime[42] ,cs[21];10 int n ;11 12 void get_prime()13 {14 memset(prime,0,sizeof(prime));15 prime[1] = 1 ;16 for(int i = 2 ; i < 40 ; i ++)17 {18 if(prime[i] == 0)19 {20 for(int j = i*i ; j < 40 ; j += i)21 prime[j] = 1 ;22 }23 }24 }25 26 void DFS(int s,int cnt)27 {28 if(cnt == n)29 {30 if(prime[cs[n]+1]) return ;31 for(int i = 1 ; i <= n - 1; i++)32 cout << cs[i] <<" " ;33 cout << cs[ n ]<<endl ;34 return ;35 }36 for(int i = 1 ; i <= n ; i++)37 {38 if(!vis[i] && !prime[s+i])39 {40 cs[++cnt] = i ;41 vis[i] = true ;42 DFS(i,cnt) ;43 cnt -- ;44 vis[i] = false ;45 }46 }47 }48 int main()49 {50 int casee = 1 ;51 get_prime() ;52 while( cin >> n )53 {54 memset(vis,false,sizeof(vis)) ;55 cout << "Case "<<casee++ <<":" << endl ;56 vis[1] = true ;57 cs[1] = 1;58 DFS(1,1) ;59 cout << endl ;60 }61 return 0 ;62 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。