HDOJ-1560(迭代加深搜索问题)

DNA sequence

HDOJ-1560

*本题是迭代加深搜索问题,主要是要理解题目,题目中一定是有解的,所以为了找最小的解,可以从小的搜索深度开始逐渐增加。
*这里有个技巧就是,如果本次指定开始迭代搜索的深度之后没有找到解,那么需要用一个临时数组将每个字符串中已经匹配好的字符数存起来。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
int n;
char chain[8][5];
int p[8];//表示第i个字符串已经匹配好的字符数
int charNums[8];//表示第i个字符串的长度
bool flag=false;
char dna[4]={'A','C','G','T'};
int remainChars(){
    int maxs=0;
    for(int i=0;i<n;i++){
        maxs=max(maxs,charNums[i]-p[i]);
    }
    return maxs;
}
void dfs(int depth){
    if(flag)
    return;
    if(remainChars()==0){//所有字符串中带匹配的字符数都为0个的话,则搜索结果找到了
        flag=true;
        return;
    }
    if(remainChars()>depth)
    return;

    int temp[8];
    for(int i=0;i<n;i++){//开一个辅助数组,先将每个字符串已经匹配好的字符数存起来,如果后序没有找到正确结果再复制回去
        temp[i]=p[i];
    }
    for(int j=0;j<4;j++){
        bool find=false;
        for(int i=0;i<n;i++){
            if(chain[i][p[i]]==dna[j]){
                p[i]++;//对于每一个属于dna的字符,对于每个n个字符串中待匹配位置的字符和它相符,待匹配位置都加一
                find=true;
            }
        }
        if(find){

            dfs(depth-1);
            if(flag){//如果递归回来以后发现找到了,则
                return;
            }
            for(int i=0;i<n;i++){
                    p[i]=temp[i];
            }
        }
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        int maxs=0;//表示初始时就需要传入迭代搜索里面的最小搜索深度
        flag=false;
        memset(p,0,sizeof(p));
        //memset(chain,'\0',sizeof(chain));//
        for(int i=0;i<n;i++){
            cin>>chain[i];
            int len=strlen(chain[i]);
            charNums[i]=len;
            maxs=max(maxs,len);
        }
        while(1){//对于每个循环,每次迭代深度都增加一,知道找到结果。
            dfs(maxs);
            if(flag){
                cout<<maxs<<endl;
                break;
            }
            maxs++;
        }
    }
    //system("pause");
    return 0;
}
posted @ 2019-08-05 21:15  Garrett_Wale  阅读(125)  评论(0编辑  收藏  举报