hdu1016 Prime Ring Problem(dfs)
搜索的水很深啊,还是先从简单的题做起吧
题目很容易理解,给定大于0小于20的数字n;
求出由n个数字组成的环;
该环每相邻的两个数之和为素数
这n个数字有1,2....n-1,n组成,不能有重复!
每个环从都1开始
输出按照字典序从小到大输出所有可能;
原题要求:
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 29191 Accepted Submission(s): 13001
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.
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.
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
#include <stdio.h> #include <string.h> int prime[41];//最大数不超过20,所以相邻数的和小于40 int vis[21];标记数组 int a[21];记录数组 int n;全局变量,便于多个函数调用 int init() { memset(vis,0,sizeof(vis));//每一次输入n,进行的初始化函数 memset(a,0,sizeof(a)); } int dfs(int pos) { if(pos==n&&(prime[a[n-1]+a[0]]))//如果确定到第n个数,并且这个数和a【0】(也就是1)之和也等于素数,输出。 { printf("1"); for(int i=1;i<n;i++) printf(" %d",a[i]); printf("\n"); } else { for(int i=2;i<=n;i++)//对于每一个位置,遍历所有可能 { if(vis[i]==0)//如果没有被标记 { if(prime[i+a[pos-1]])//如果是素数 { a[pos]=i; vis[i]=1; pos++; dfs(pos); vis[i]=0;//回溯 pos--; } } } } }//这个题和我之前做的有点不一样,这个DFS没有return 0 等结束语句,因为要求得所有可能,一个个遍历,并非求出结果就返回,所以没有
//由于之前做题的惯性思维,习惯性的加上return 导致代码很复杂,在这里学习了http://www.cnblogs.com/jiangjing/archive/2013/02/04/2891621.html 这个博客主的代码,十分感谢。
int main() { prime[0]=1; prime[1]=1;//0,1不是素数,赋值1 for(int i=2;i<41;i++) { for(int j=i*i;j<41;j+=i)//将所有合数赋值为1 prime[j]=1; } for(int i=0;i<41;i++) if(prime[i]==0) prime[i]=1;//再进行0,1对调//因为之前发现memset不能将数组元素直接赋值为1,所以这里简单转换了一下 else prime[i]=0; int cs=0; while(scanf("%d",&n)!=EOF) { cs++; printf("Case %d:\n",cs); init();//初始化 a[0]=1; dfs(1); printf("\n"); } return 0; }