Prime Ring time limit: +Ms | Memory Limit:65535KB Difficulty:2
-
Describe
-
There is an integer n, the number from 1 to n is not repeated into a ring, and each adjacent two numbers (including the end) and the sum is a prime number, called the prime ring.
For the sake of brevity, we stipulate that each prime ring starts from 1. For example, it is a prime ring of 6.
-
Input
-
There are several sets of test data, one for each set of N (0<n<20), and n=0 for the end of the input.
-
Output
-
The first row of each group outputs the corresponding case sequence number, starting with 1.
If there is a prime ring that satisfies the test instructions narrative, the output is from small to large.
Otherwise output no Answer.
-
Sample input
-
6830
-
Sample output
-
Case 1:1 4 3 2 5 2Case 6 5 2 3 4Case 2:1 2 3 8 5 6 7 2 5 8 3 4 7 4 7 6 5 8 3 6 7 4 3:no Answer
-
Source
-
HDU adaptation
-
Uploaded by
-
acm_ messages
This question hdoj also has, starts to do this question, also did not think so many, directly knocks the previous code, has been tle, later learned a little new thing, does not exist has the odd number element the prime circle (each element dissimilarity). However, 1 can form a self-ring, requiring special judgment.
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
usingnamespaceStd
intN, dis[ -], vis[ -];
BOOLIs_prime (intA
{
if(!a | | a = =1)
returnfalse;
if(A = =2|| A = =3)
returntrue;
for(inti =2; I <= sqrt (a); i++)
if(a% i = =0)
returnfalse;
returntrue;
}
voidDfs (intA
{
if(A = = N && is_prime (1+dis[n-1]))
{
for(inti =0; I < n; i++)
printf (i==0?"%d":"%d", Dis[i]);
printf"\ n");
return;
}
Else
{
for(inti =2; I <= N; i++)
{
if(!vis[i] && is_prime (i+dis[a-1]))
{
Vis[i] =1;
Dis[a] = i;
Dfs (A +1);
Vis[i] =0;
}
}
}
}
intMain ()
{
intQ =1;
while(~SCANF ("%d", &n), N)
{
printf"Case %d:\n", q++);
if(n = =1){//1 A special sentence is required.
printf"1\n");
Continue;
}
if(n&1){//pruning, there is an odd number (except 1) of a different element of the prime ring does not exist.
printf"No answer\n");
Continue;
}
dis[0] =1;
memset (Vis,0,sizeof(VIS));
Dfs (1);
}
return 0;
}
Nanyang oj488--Prime Ring (DFS + pruning)