要求: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) ;
}
}