HDOJ-1560 (iterative deepening search problems)

DNA sequence

HDOJ-1560

This problem is iterative deepening search problem, mainly to understand the subject, the title must be solvable, so in order to find the smallest of the solution, you can search small depth gradually increases.
Here is a skill that, if no solution is found after the current iteration depth specify the start of the search, you need to use a temporary array to match each string has a good number of characters saved.

#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;
}

Guess you like

Origin www.cnblogs.com/GarrettWale/p/11305584.html