HDU 1560 IDA*

要求:n个字符串(1 <= n <= 8),每个字符串长度不超过5,求一个字符串使这n个字符串都是它的子序列,输出所求序列的最短长度。例如给出:4个字符串"ACGT","ATGC","CGTT" , "CAGT",拼接成下图,则输出最短长度8。

方法:IDA*

1.IDA*是迭代加深搜索,就是限制DFS的深度,若当前深度搜索不到结果,那么增加深度继续搜索。

2.搜索即可。

3.代码中的注释解释了这个算法。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std ;
char DNA[4] = {'A' , 'C' , 'G' , 'T'} ;
int n ;
int maxn ;
int pos[10] ;//pos[i]表示第i个序列拼接到了第pos[i]个位置 
struct node
{
	char s[10] ;
	int len ;
}a[10] ;
int get()
{
  int i ;
  int ans = 0 ;
  for(i = 0 ; i < n ; i ++)
      ans = max(ans , a[i].len - pos[i]) ;
  return ans ;  	
}
int dfs(int depth)
{
	int i , j ;
	int temp[10] ;
	if(depth + get() > maxn) return 0 ;//比dfs多了一个限制条件  
	if(!get()) return 1 ;
	memcpy(temp , pos , sizeof(pos)) ;//先用temp储存pos 以便回溯时复原 
	for(i = 0 ; i < 4 ; i ++)
	{
		int flag = 0 ;
		for(j = 0 ; j < n ; j ++)
		{
			if(a[j].s[pos[j]] == DNA[i])//第depth列用DNA[i]进行拼接 序列尽可能地拼接 
			{
				flag = 1 ; 
				pos[j] ++ ;
			}
		}
		if(flag)//一旦可以拼接,则进行下一层搜索 
		{
			if(dfs(depth + 1))
			   return 1 ;
			memcpy(pos , temp , sizeof(temp)) ;
		}
	}
	return 0 ;
}
int main()
{
   int t ;
   int i , j ;
   scanf("%d" , &t) ;
   while(t --)
   {
      scanf("%d" , &n) ;	
      for(i = 0 ; i < n ; i ++)
      {
      	 scanf("%s" , a[i].s) ; 
      	 a[i].len = strlen(a[i].s) ;
	  }
      maxn = 0 ;
      memset(pos , 0 , sizeof(pos)) ;
	  while(1) 
	  {
	    if(dfs(0)) break ;
		maxn ++ ; //maxn即为搜索深度 
	  }
	  printf("%d\n" , maxn) ;    
   }	
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值