hdoj 1016 素数圆环问题(深度优先搜索z和道题 )

博客主要讨论了ACM竞赛中的一个问题——素数圆环问题,该问题导致的主要困难是算法运行超时。作者通过研究网上代码找到了解决超时的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        这道题出现的最大问题是超时,后来参照网上的代码才明白原因:

  按照自己的思想,先判断数字是否重复,此过程经历一系列递归,然后又在这些不重复的序列循环搜索素数序列,这样就经历了两回循环,必然耗时,而进行优化后,可以在递归过程用两个条件判断,既要求数字不重复,又要求相邻和两端必须是素数!大大减少了运行时间!


                                 Prime Ring Problem

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 24   Accepted Submission(s) : 7
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
     
       
                                       
AC码
#include <cstdio>
#include <cstring>
int n,m,a[21],arr[21]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20},mark[21];
int c[50];
int k=1,j;
void dfs(int v)
{
	 if(v==n&&c[a[0]+a[n-1]])  
     {  
              for(int r=0;r<n;r++)  
               {  
                      if(!r)printf("%d",a[r]);  
                      else printf(" %d",a[r]);  
               }  
              printf("\n"); 
			  return;
	 }
    /*if(v >= n){
    	for(int i=1;i<n;i++)     //这种方法超时 
    	{
    		if(!c[a[i]+a[i-1]])			
    		return;
    		if(!c[a[0]+a[n-1]])        
    		return;  
		}
		if(a[0]==1)  
		{
			for(int i = 0;i < n;i++)
           {	
           		
				   printf("%d ",a[i]);
		   } 
        printf("\n");
        return ;
		}*/
        

    for(int j = 1; j< n;j++)
	{
        if(!mark[j])   //打印出来的数字不能重复 
		{
        	if(c[a[v-1]+arr[j]]) //同时判断必须是素数 
            {
            	mark[j] = 1;  //标记为已用过 
            	a[v] = arr[j]; 
            	dfs(v+1);
            	mark[j] = 0;  //如果退回来一步就必须把原位置标记为没用过 
			}
			else continue;
        }
    }
    
}
int main()
{
    while(scanf("%d",&n)==1)
	{
        memset(mark,0,sizeof(mark));
        c[2]=c[3]=c[5]=c[7]=c[11]=c[13]=c[17]=c[19]=c[23]=c[29]=c[31]=c[37]=c[39]=1; 
		printf("Case %d:\n",k++) ;
		a[0]=1;//因为a[0]已经确定,直接写出来可以节省判断的时间 
        dfs(1);   //a[0]已经打印,从第二位开始判断 
        printf("\n");
    }
    
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值