HDU - 1016 Prime Ring Problem
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
问题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016
问题简述:要求输出从1到n的之间相邻的数相加为素数的序列。(第一个和最后一个也要满足要求)
问题分析:判断素数+dfs
AC通过的C++语言程序如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include <algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
const int maxn = 100005;
int num[maxn];
bool vis[maxn];
int n;
bool prime(int x)
{
for (int i = 2; i*i <= x; i++)
{
if (x%i == 0) return 0;
}
return 1;
}
void dfs(int x)
{
if (x == n && prime(num[n - 1] + 1))
{
cout << 1;
for (int i = 1; i < n; i++)
{
cout << " " << num[i];
}
cout << endl;
}
if (x == n) return;
for (int i = 2; i <= n; i++)
{
if (!vis[i] && prime(num[x - 1] + i))
{
vis[i] = 1;
num[x] = i;
dfs(x + 1);
vis[i] = 0;
}
}
}
int main()
{
int z = 1;
while (cin >> n)
{
memset(num, 0, maxn);
memset(vis,0, maxn);
vis[1] = 1;
num[0] = 1;
cout << "Case " << z << ":" << endl;
dfs(1);
cout << endl;
z++;
}
return 0;
}
上一篇: python发送伪造的arp请求