UVa 524 - Prime Ring Problem

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

題目網址
中文網址

Solution

每次選一個數,只要加上前一個數後仍為質數就 ok 了。直到最後一個,再去檢查是否和第一個相加完後也為質數。

Code

UVa 524UVa 524 - Prime Ring Problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<cstdio>
#define N 17

bool notPrime[32] = { true, true };
void backtracking(int n, int count);
int main()
{
int i, j;
for (i = 2; i < 32; i++)
if (!notPrime[i])
for (j = i + i; j < 32; j += i)
notPrime[j] = true;

int n,Case=0;

while (scanf("%d", &n) != EOF)
{
if (Case)
putchar('\n');
printf("Case %d:\n", ++Case);

backtracking(n, 0);
}

return 0;
}
void backtracking(int n, int count)
{
static bool isVisit[N];
static int sol[N];
int i;

if (!count)//init
{
for (i = 0; i <= n; i++)
sol[i] = isVisit[i] = 0;
sol[1] = 1;
isVisit[1] = true;
count++;
}
else if (count == n)
{
if (!notPrime[1 + sol[count]])//確認頭+尾是質數
{
putchar('1');
for (i = 2; i <= n; i++)
printf(" %d", sol[i]);
putchar('\n');
}

return;
}

for (i = 2; i <= n; i++)
{
if (!isVisit[i] && !notPrime[i + sol[count]])
{
isVisit[i] = true;
sol[count + 1] = i;
backtracking(n, count + 1);
isVisit[i] = false;
}
}

}