HDU-1016Prime Ring Problem

it2024-07-13  73

 Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

 

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1016

 

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   总结 

   昨天学了DFS,今天自己做了一道题,从6点半到8点半,在提交时我还以为不会过,毕竟除了A+B的题,我没一次性AC过一道题,在测试最大数据时,黑框跑了34秒还没停下来,我以为我要超时了,但是并没有,好高兴。网上搜了一下,发现自己的代码还可以优化,可以将素数打表,每次去查表,不用循环,应该能节省一大堆时间。

#include<iostream> #include<cstdio> #include<memory.h> using namespace std; int N; int temp[25],cir[25]; int is_prime(int x) //判断是否为素数 { for(int i=2;i*i<=x;i++) if(x%i==0) return 0; return 1; } void dfs(int a,int n) //深度搜索,查找序列 { int a1; if(n==N&&is_prime(a+1)){ //停止搜索条件 for(int i=1;i<N;i++) cout <<cir[i]<<' '; cout <<cir[N]<<endl; return; } for(int i=2;i<=N;i++){ a1=i; if(temp[a1]==1) continue; if(!temp[a1]&&a1>=1&&a1<=N&&is_prime(a1+a)){ cir[n+1]=a1; temp[a1]=1; dfs(a1,n+1); temp[a1]=0; } } } int main() { int count1=1; while(scanf("%d",&N)==1&&N){ cout <<"Case "<<count1++<<":"<<endl; memset(temp,0,sizeof(temp)); memset(cir,0,sizeof(cir)); temp[1]=1; cir[1]=1; dfs(1,1); cout <<endl; } }

 

转载于:https://www.cnblogs.com/wangdongkai/p/5267191.html

最新回复(0)