输入输出样例
示例
输入
6 2 4 6
5 3 4 6 4 9
1 2
1 2 3
1 3 4
2 3 5
4 5 6
输出
16
暴力dfs就行了,我们要想好我们拥有的条件:
1.N个种子的种植时间
2.M个已有种子
3.K种杂交方案
4.求种出T的最短时间
怎么去dfs呢?
首先边界条件很好设置,如果在当前条件下已经种出来了,那么我们可以直接返回种出他要的时间,这里是period
然后,我们现在知道要种出什么,所以我们传入的参数应该有要种出的种子的编号,对这个编号,我们搜索所有能种出它的方案,对杂交得到他的两个种子继续进行判断,如果当前还没种出来,那就得继续种,直到找到一个种子编号c,另外两个种子a,b也早就已经存在或者种出来了,这个时候我们要更新一些结构,比如说当前种子已经拥有plant。
另外,我们要找出最小的种植时间,这是两个时间比较得到的:种植a,b的最大时间和种植得到a或b的最大时间,两个最大时间之和,以及当前period谁比较小,就得到了要时间量。所以period的初值设定要把已经存在的种子设置成0,因为已经有了,然后其余的初值要设置大一点,以便取min
#include <bits/stdc++.h>
using namespace std;
const int N=2001;
const int K=100001;
int w[N];//保存每个种子的种植时间
int cross[K][3];//保存方案
int period[N];//保存以当前M个种子出发,最短多久可以杂交出对应下标种子
bool plant[N];//是否种出或者说已经存在
int dfs(int t,int k)
{
if(plant[t]) return period[t];//避免重复求
for(int i=1;i<=k;++i)
{
if(cross[i][2]==t)
{
int a=cross[i][0];
int b=cross[i][1];
if(!plant[a]) dfs(a,k);
if(!plant[b]) dfs(b,k);
if(plant[a]&&plant[b])
{
period[t]=min(period[t],max(w[a],w[b])+max(period[a],period[b]));
}
}
}
plant[t]=true;
return period[t];
}
int main()
{
// 请在此输入您的代码
int n,m,k,t,tmp;
scanf("%d%d%d%d",&n,&m,&k,&t);
memset(period,0x3f3f3f3f,sizeof(period));
for(int i=1;i<=n;++i)
scanf("%d",&w[i]);
for(int i=1;i<=m;++i)
{
scanf("%d",&tmp);
plant[tmp]=true;
period[tmp]=0;//已经有这颗种子了 直接得到不需要时间
}
for(int i=1;i<=k;++i)
{
scanf("%d%d%d",&cross[i][0],&cross[i][1],&cross[i][2]);
}
cout<<dfs(t,k);
return 0;
}
这里还有优化结构的空间,改善方案的存储方式:原来我们是按照方案数来存的,现在我们以杂交出的种子为下标,杂交的两个种子作为成分存储在一个vector中,这样在递归的时候可以不用遍历所有的方案数:
#include <bits/stdc++.h>
using namespace std;
const int N=2001;
const int K=100001;
typedef pair<int,int> PII;
vector<PII>cross[N];
int w[N];
// int cross[K][3];
int period[N];
bool plant[N];
int dfs(int t)
{
if(plant[t]) return period[t];
for(int i=0;i<cross[t].size();++i)
{
int a=cross[t][i].first;
int b=cross[t][i].second;
if(!plant[a]) dfs(a);
if(!plant[b]) dfs(b);
if(plant[a]&&plant[b])
{
period[t]=min(period[t],max(w[a],w[b])+max(period[a],period[b]));
}
}
plant[t]=true;
return period[t];
}
int main()
{
// 请在此输入您的代码
int n,m,k,t,tmp;
scanf("%d%d%d%d",&n,&m,&k,&t);
memset(period,0x3f3f3f3f,sizeof(period));
for(int i=1;i<=n;++i)
scanf("%d",&w[i]);
for(int i=1;i<=m;++i)
{
scanf("%d",&tmp);
plant[tmp]=true;
period[tmp]=0;//已经有这颗种子了 直接得到不需要时间
}
for(int i=1;i<=k;++i)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
cross[c].push_back({a,b});
}
cout<<dfs(t);
return 0;
}