HDU1560 DNA sequence (IDA*)

来源:互联网 发布:mac电脑免费翻墙 编辑:程序博客网 时间:2024/06/03 12:43

题目大意:给你n(n<=8)个字符串,每个字符串的长度不超过5,现在让你找出一个最短的母串,使得这n个字符串为这个母串的子串。


思路:搜索。很容易看出来最少步数大于等于最长的字符长度,因此估值函数h() =  同一字符串中所有剩余没匹配字母长度的最大值


#include<cstdio>#include<cstring>#define Max(a,b) a>b?a:busing namespace std;int n;struct T{char s[10];int len;}a[10];int pos[10];//字符串i现在匹配到的位置char letter[5] = {'A','G','C','T'};int maxn;int depth;int hash[30];int get_h()//估值函数{int w[4] = {0};//所有剩余长度的最大值for(int i = 1; i <= n; i++){int t[4] = {0};for(int j = pos[i]; j < a[i].len; j++){t[ hash[ a[i].s[j] - 'A' ] ]++;}for(int j = 0; j < 4; j++) w[j] = Max(w[j],t[j]);}return w[0] + w[1] + w[2] + w[3];}bool IDAstar(int cur){if(cur + get_h() > depth) return false;//当前进行的深度加上至少还要匹配的深度,如果它比限定的深度还要大,那么我们就可以剪枝了if(get_h() == 0) return true;int temp[10];bool flag = 0;for(int i = 0; i < 4; i++)//枚举字母{memcpy(temp,pos,sizeof pos);for(int j = 1; j <= n; j++){if(letter[i] == a[j].s[pos[j]])//当前一个字符可以匹配,因此该字符串向后移动一位{flag = 1;pos[j]++;}}if(flag){if(IDAstar(cur+1)) return true;//迭代下一层memcpy(pos,temp,sizeof temp);//复原}}return false;}int main(){int T;scanf("%d",&T);hash[0] = 0; hash['G'-'A'] = 1; hash['C'-'A'] = 2; hash['T'-'A'] = 3;while(T--){scanf("%d",&n);maxn = 0;for(int i = 1; i <= n; i++){scanf("%s",a[i].s);a[i].len = strlen(a[i].s);if(a[i].len > maxn)maxn = a[i].len;pos[i] = 0;}for(depth = maxn; ; depth++)//枚举匹配后长度{if(IDAstar(0)) {printf("%d\n",depth);break;}}}}


0 0