HDU 1016 Prime Ring problem---classic DFS

Source: Internet
Author: User

Idea: The first number filled 1, after each number to judge the number and the previous number to add whether it is a prime, is filled, and then marked, near one-step recursive solution. Then remember to backtrack and continue to judge the sum of the next and previous numbers as the number of primes.

/*HDU 1016 Prime Ring Problem---classic DFS*/#include<cstdio>#include<cstring>intN;BOOLprimer[ $], visit[ -];//Primer The Prime number table, visit mark whether to accessinta[ -];//array A stores the number of placements/*40 within the prime number of the table*/voidGetprimer () {//because n Max is 20, so just hit theprimer[0] = primer[1] =1;//1 means not a prime number     for(inti =2; I <7; ++i) {         for(intj = i*i; J < +; j+=i) {Primer[j]=1;//1 means not a prime number}//For (j)}//For (i)}/*DFS Search num is the number of filled numbers*/voidDfsintnum) {    inti; //All completed and the sum of the first is the prime number output    if(num = n &&!primer[a[num-1] + a[0]]){         for(i =0; I < num-1; ++i) {printf ("%d", A[i]); } printf ("%d\n", A[i]); return; }    Else{         for(i =2; I <= N; ++i) {            //the number has not been used and the sum of the previous number is prime            if(!visit[i] &&!primer[a[num-1] +i]) {A[num]=i; Visit[i]=1; DFS (Num+1);//Recursive fill numberVisit[i] =0;//Backtracking            }        }    }}intMain () {intKase =0;    Getprimer ();  while(SCANF ("%d", &n) = =1) {memset (visit,0,sizeofvisit); printf ("Case %d:\n", ++Kase); visit[1] =1;//1 used.a[0] =1;//the first number is 1 .Dfs1); printf ("\ n"); }    return 0;}
View Code

HDU 1016 Prime Ring problem---classic DFS

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.