作物杂交(DFS)
本来一开始我是直接跳过的,因为看到标签有动态规划,但是仔细看看题解,发现主要还是用的DFS。这里的DFS也很有动态规划的味道了。难在递推公式:
sumtime[goalSeed] = min(sumtime[goalSeed], max(cost[a], cost[b]) + max(sumtime[a], sumtime[b]));
因为本来的题解有点晦涩,就用我自己的方式写了一下,比如 a+b-->c,计算得到c的总时间,就应该是 之前算的时间,以及 现在算的时间,取最小那个,而现在算的时间=(培育出a和b的时间)+(获得a和b的时间)。注意这里措辞,一个是培育,表示ab种子生长杂交的时间;一个是获得,表示从起始种子开始,经过一系列操作最终得到ab种子的时间。
AC:
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
// 我的思路没有大错,难点在于递推公式 :
// f[t] = min(f[t], max(w[a], w[b]) + max(f[a], f[b]));
// f表示t号植株的最小杂交时间,他的值应该为 之前计算的:现在计算的
// 现在计算的 = 直属种子杂交的最大时间+直属种子的最小获得时间(最久的那个获得了才算都获得了)
const int N = 1e5 + 3;
int n, m, k, t;
int cost[N] = { 0 }; //植株生长杂交时间
vector<vector<pair<int, int>>>plant(N);
bool book[N] = { 0 }; //表示已经计算过 获得该种子的最短时间了
int sumtime[N] = { 0 }; //获得该植株的总时间
int dfs(int goalSeed)
{
if (book[goalSeed] == true) return sumtime[goalSeed];
for (int i = 0; i < plant[goalSeed].size(); i++) //遍历能得到这个种子的所有组合
{
int a = plant[goalSeed][i].first, b = plant[goalSeed][i].second;
if (!book[a]) dfs(a); //还没有确定获得a的总时间,那就先去算算a的,因为在计算中自动保存了,所以此处就不需要接收
if (!book[b]) dfs(b);
sumtime[goalSeed] = min(sumtime[goalSeed], max(cost[a], cost[b]) + max(sumtime[a], sumtime[b]));
}
book[goalSeed] = true;
return sumtime[goalSeed];
}
int main()
{
cin >> n >> m >> k >> t; //种子类别、初始种子、杂交方案、目标种子
for (int i = 1; i <= n; i++)
cin >> cost[i];
int ori;
memset(sumtime, 0x3f3f3f3f, sizeof(sumtime)); //初始化
for (int i = 0; i < m; i++)
{
cin >> ori;
sumtime[ori] = 0; //直接获得
book[ori] = true; //标记
}
int a, b, c;
for (int i = 0; i < k; i++)
{
cin >> a >> b >> c;
plant[c].push_back({ a,b });
}
cout << dfs(t) << endl;
return 0;
}