版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39562952/article/details/82897752
思路:IDDFS是每次按照限制的深度进行搜索,如果在k深度没有找到解,则进行k+1深度的搜索;
这题的做法就是按照从max_size的深度开始增加深度,如果找到解直接return;
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <cstring>
#include <climits>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stdio.h>
#include <sstream>
#include <map>
#define esp 1e-4
using namespace std;
/*
迭代加深搜索,如果当前搜索深度+最少要搜索的深度>限制的深度,则return;
*/
int n;
char str[10][10];
int si[10];//代表每个字符串的长度
int deep;//限制深度
int ans;
char key[5] = "ACGT";
void dfs(int cnt, int len[])//cnt 代表当前的搜索深度,len[i]代表i字符串已经匹配到的位置
{
if (cnt > deep)
return;
int maxx = 0;//代表每个字符串剩余要匹配的字符个数
for (int i = 0; i < n; i++)
{
maxx = max(maxx, si[i] - len[i]);
}
if (maxx == 0)
{
ans = cnt;
return;
}
if (cnt + maxx > deep)//当前搜索深度+最少要搜索的深度>限制的深度
return;
int pos[10];
int flag = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < n; j++)
{
if (str[j][len[j]] == key[i])
{
flag = 1;//代表str[0-9]匹配到的位置中有key[i],就构成了一个结果
pos[j] = len[j] + 1;
}
else
pos[j] = len[j];
}
if (flag)
dfs(cnt + 1, pos);
if (ans != -1)
return;
}
}
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> n;
int max_size = 0;//这些字符串中最长的长度
for (int i = 0; i < n; i++)
{
cin >> str[i];
si[i] = strlen(str[i]);
if (si[i] > max_size)
max_size = si[i];
}
int pos[10] = { 0 };//当前搜索到的位置,一开始都是从0开始
deep = max_size;
ans = -1;
while (1)
{
dfs(0, pos);
if (ans != -1)
break;
deep++;//增加搜索深度
}
cout << ans << endl;
}
return 0;
}