当前位置:编程学习 > C/C++ >>

HDU1016-Prime Ring Problem(DFS)

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
 
 
 
分析:
题意:输入正整数n,把整数1,2,3,…,n组成一个环,使得相邻两个整数之和均为素
 
数。输出时从整数1开始逆时针排列。同一个环应恰好输出一次。
 
素数环问题的程序实际上主要由求素数和整数1,2,3,…,n的排列构成。
 
运用DFS模型来回溯、其处理效率提高、看代码就能明白整个处理过程。
 
#include<iostream>  
#include<string.h>  
#include<stdio.h>  
#include<ctype.h>  
#include<algorithm>  
#include<stack>  
#include<queue>  
#include<set>  
#include<math.h>  
#include<vector>  
#include<map>  
#include<deque>  
#include<list>  
using namespace std;  
bool is_prime(int x)   //判数一个整数x是否是一个素数  
{  
    for(int i = 2; i*i <= x; i++)  
    {  
        if(x % i == 0)  
            return 0;  
    }  
    return 1;  
}  
int n, A[50], isp[50], vis[50];  
int w=1;  
void dfs(int p)  
{  
    if(p == n && isp[A[0]+A[n-1]])  //递归边界,别忘测试第一个数和最后一个数  
    {  
        for(int i = 0; i < n-1; i++)  
            printf("%d ", A[i]);  
        printf("%d\n",A[n-1]);  
    }  
    else  
        for(int i = 2; i <= n; i++)  //尝试放置每个数i  
            if(!vis[i] && isp[i+A[p-1]])  
            {  
       //如果i没有用过,并且与前一个数之和为素数  
                A[p] = i;  
                vis[i] = 1; //设置标记  
                dfs(p+1);  
                vis[i] = 0; //清除标记  
            }  
}  
int main()  
{  
    while(scanf("%d", &n)!=EOF)  
    {  
        for(int i = 2; i <= n*2; i++)  
            isp[i] = is_prime(i);  
        memset(vis, 0, sizeof(vis));  
        A[0] = 1;  
        printf("Case %d:\n",w++);  
        dfs(1);  
        printf("\n");  
    }  
    return 0;  
}  

 

 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,