码迷,mamicode.com
首页 > 其他好文 > 详细

hdoj 1016 Prime Ring Problem

时间:2015-08-18 21:04:45      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description
A 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.

技术分享
 

 

Input
n (0 < n < 20).
 

 

Output
The 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 Input
6 8
 

 

Sample Output
Case 1: 1 4 3 2 5 6
     1 6 5 2 3 4
Case 2: 1 2 3 8 5 6 7 4
     1 2 5 8 3 4 7 6
     1 4 7 6 5 8 3 2
     1 6 7 4 3 8 5 2
 
 1 #include <stdio.h>
 2 #include <string.h>
 3 int n;
 4 int vis[30], a[30];
 5 int judge(int s)
 6 {
 7     int flag = 1;
 8     for(int i = 2; i <= s/2; i++)
 9     {
10         if(s%i == 0)
11         {
12             flag = 0;
13             break;
14         }
15     }
16     return flag;
17 } 
18 void dfs(int s, int cnt)
19 {
20     int i, j;
21     if(cnt  == n+1 && judge(a[1]+a[n]))
22     {
23         for(j = 1; j < n+1; j++)
24         {
25             if(j != 1)
26                 printf(" ");
27             printf("%d", a[j]);
28         }
29         printf("\n");
30         return ;
31     }
32     for(i = 1; i <= n; i++)
33     {
34         if(judge(i + s) && !vis[i])
35         {
36             a[cnt] = i;
37             vis[i] = 1;
38             dfs(i, cnt + 1);
39             vis[i] = 0;
40             
41         }
42     }
43     return ;
44 }
45 int main()
46 {
47     int num = 1;
48     while(~scanf("%d", &n))
49     {
50         printf("Case %d:\n", num++);
51         memset(vis, 0, sizeof(vis));
52         vis[1] = 1;
53         a[1] = 1;
54         dfs(1, 2);
55         printf("\n");
56     }
57     return 0;
58 } 

 

hdoj 1016 Prime Ring Problem

标签:

原文地址:http://www.cnblogs.com/digulove/p/4740447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!