版权声明:那个,最起码帮我加点人气吧,署个名总行吧 https://blog.csdn.net/qq_41670466/article/details/84789680
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1560
题意大致就是:给你几个字符序列,然后问你一个最短的序列的长度:这个序列要可以组成那几个字符序列
思路:我一开始想的是双拓扑排序来构建优先关系,但后来失败了。
这道题的思路其实可以理解为一种模拟,假设这里有一个长度为deep的区间,(deep为之前序列的最长的长度)那么我们要做的的就是模拟每个格子应该填什么才能让这个格子最短,于是我们可以进行dfs模拟,先假设第一个格子是a,如果各序列里有满足第一个字符是a的那么该序列的指针向下移动,其余不变,然后在模拟第二个格子,。。。。其中在模拟时为了剪枝使用了个预估函数,这个预估函数作用是预判理想情况下这个格子够不够用,如果理想情况都不够那么说明这个方法错误,返回,改变方法,如果所有的方法所得到的格子长度都比deep大,那么退出,deep++,再进行同样的过程。知道找到符合长度等于deep的情况,这个过程就是IDA*算法的过程。
反思:我在这道题的理解还是不到位,没有想到这道题其实本质上还是一种枚举的问题,这个点才是这个题的核心思想,你只要想到这个题的思路是枚举,才能想到搜索的思路,
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
int n, deep;
char c[10] = "ACGT";
string a[10];
int pos[10];
int geth()//获取剩下的字符序列要想全部匹配还需要的最大长度;
{
int ans = 0;
for (int i = 1; i <= n; i++)
ans = max(ans, (int)a[i].size()-pos[i]);
return ans;
}
int dfs(int step)
{
if (step + geth() > deep)
return 0;
if (geth() == 0)
return 1;
int tem[10];
for (int i = 0; i < 4; i++)
{
int flag = 0;
for (int j = 1; j <= n; j++)
tem[j] = pos[j];
for (int j = 1; j <= n; j++)
{
if (a[j][pos[j]] == c[i])
{
flag = 1;
pos[j]++;
}
}
if (flag)
{
if (dfs(step + 1))
return 1;
for (int j = 1; j <= n; j++)
pos[j] = tem[j];
}
}
return 0;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
//memset()
scanf("%d", &n);
deep = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
deep = max(deep, (int)a[i].size());
pos[i] = 0;
}
while (1)
{
if (dfs(0)) break;
deep++;
}
printf("%d\n", deep);
for (int i = 1; i <= n; i++)
a[i].clear();
}
//system("pause");
return 0;
}