HDU 1016 prime ring problem (prime screening + DFS)

Source: Internet
Author: User

Question Link

Meaning: arrange n numbers on the ring. The sum of each two adjacent numbers must be a prime number, and the first number must be 1. Output all possible arrays.

Idea: first create a prime number table. And then go through the search loop .....

 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 }
View code

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.