題目連接php
給定N個DNA字符串,找到最短的字符串使N個字符串都是它的子序列(不連續)ios
又是典型的IDA* 迭代加深搜索思路,用一個數組保存每次搜索到對於N個字符串的下標,當每一個下標都到了字符串的結尾的時候即說明解出了答案。 爲防止超時,當此時深度+至少還要加深的深度>限制值時就返回上一層狀態。c++
#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; }