HDU 1016 素數環(深搜)

來源:互聯網
上載者:User

標籤:des   style   blog   java   color   os   

Prime Ring ProblemTime Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 25134    Accepted Submission(s): 11222Problem DescriptionA ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.Note: the number of first circle should always be 1. Inputn (0 < n < 20). OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.You are to write a program that completes above process.Print a blank line after each case. Sample Input68 Sample OutputCase 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2

 

題目意思就是給一個數n,1-n數字圍成一個環,環中每兩個相鄰的數字相加為素數,把滿足條件所有環輸出,1始終為第一個數字。

感覺是深搜,於是水過了。。

代碼:

 1 #include <stdio.h> 2 #include <iostream> 3 #include <string.h> 4 #include <algorithm> 5 #include <math.h> 6 #include <vector> 7 using namespace std; 8  9 int used[20];10 int p[40];11 int n;12 vector<int>a;13 int kase;14 void dfs(int k)15 {16     if(k>=n)17     {18         if(!p[a[0]+a[n-1]])                 //數組首位相連構成環,首位相加為素數才滿足條件 19         {20             printf("%d",a[0]);21             for(int i=1;i<a.size();i++)22         printf(" %d",a[i]);23         printf("\n");24         }25         return;26     }27     for(int i=2;i<=n;i++)28     {29         int b=a[a.size()-1];30             if(!used[i]&&!p[b+i])31             {32                 a.push_back(i);33                 used[i]=1;34                 dfs(k+1);35                 a.pop_back();36                 used[i]=0;37             }38     }39 }40 main()41 {42     int i, j, k;43     memset(p,0,sizeof(p));                            44     p[1]=1;p[2]=0;45     for(i=2;i<=40;i++)                     //篩選法求素數 46     {47         for(j=2;j*i<=40;j++)48         p[j*i]=1;49     }50     kase=1;51     while(scanf("%d",&n)==1)52     {53         54             memset(used,0,sizeof(used));55             used[1]=1;56             a.clear();57             a.push_back(1);58             printf("Case %d:\n",kase++);59             dfs(1);60             cout<<endl;61     }62 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.