hdu1560DNA sequence(IDA*搜索)

题目链接

题意

给定N个DNA字符串,找到最短的字符串使N个字符串都是它的子序列(不连续)

解题思路

又是典型的IDA* 迭代加深搜索思路,用一个数组保存每次搜索到对于N个字符串的下标,当每个下标都到了字符串的结尾的时候即说明解出了答案。
为防止超时,当此时深度+至少还要加深的深度>限制值时就返回上一层状态。

AC代码

#include<vector>
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<set>
#include<cstring>
#include<functional>
#include<map>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
char dc[] = {'A','T','G','C'};
string s[10];
int n = 0;

bool idastar(int step,int *dex,int top)
{
    bool yes = 1;
    int min_len = 0;
    for(int i=0;i<n;i++){
        int len = s[i].size();
        if(dex[i] != len){
            yes = 0;
            min_len = max(min_len,len - dex[i]);
        }
    }
    if(yes)return true;
    if(min_len + step > top) return false;
    
    for(int i=0;i<4;i++){
        char c = dc[i];
        int cnt = 0;
        int pos[10];
        for(int j=0;j<n;j++){
            int len = s[j].size();
            if(dex[j]!= len){
                if (c == s[j][dex[j]]){
                    cnt++;
                    pos[j] = dex[j]+1;
                }else{
                    pos[j] = dex[j];
                }
            }else{
                pos[j] = dex[j];
                continue;
            }
        }
        if(cnt==0)continue;
        if(step <= top){
            bool ok = idastar(step + 1,pos, top);
            if (ok)
                return true;
        }
    }
    return false;
}

int main(int argc, char const *argv[])
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T = 0;
    cin >> T;
    while(T--){
        cin >> n;
        size_t top = 0;
        for(int i=0;i<n;i++){
            cin >> s[i];
            top = max(s[i].length(),top);
        }
        int dex[100];
        while(top){
            memset(dex,0,sizeof(dex));
            if(idastar(0,dex,top))break;
            top++;
        }
        cout << top << endl;
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/django-lf/p/9799080.html