我用的方法是贪心,我们只需要将所有的奶牛按照 h e a v y + s t r o n g heavy+strong heavy+strong 从大到小进行排序,用深搜枚举所有种选奶牛的方案。对于每一只奶牛,我们只有选或不选。到最后的时候,我们再按题目求出 a n s ans ans 即可。
代码
#include<bits/stdc++.h>
using namespace std;
int n,h,ans[50005],ansa=-1,cnt;
struct op{
int tall,heavy,strong;//分别表示高度,重量,载重量
}cow[505];
bool cmp(op a,op b)
{
return (a.heavy+a.strong)>(b.heavy+b.strong);//按heavy+strong由大到小排
}
void dfs(int step,int tall)
{
if(step>n)//到尽头
{
if(tall>=h)//符合题意
{
int sum=cow[ans[cnt]].heavy,sheng=cow[ans[cnt]].strong;//分别表示每头奶牛上方的总重量和还能够在牛塔最上方添加的最大重量
for(register int i=cnt-1;i>=1;i--)//寻找载重量剩下的最小值
{
sheng=min(sheng,cow[ans[i]].strong-sum);//更新
sum+=cow[ans[i]].heavy;//加上当前重量
}
if(sheng>ansa)//更新答案
{
ansa=sheng;
}
}
return;
}
cnt++;
ans[cnt]=step;
dfs(step+1,tall+cow[step].tall);//选
ans[cnt]=0;
cnt--;
dfs(step+1,tall);//不选
}
int main()
{
cin>>n>>h;
for(register int i=1;i<=n;i++)
{
cin>>cow[i].tall>>cow[i].heavy>>cow[i].strong;//输入
}
sort(cow+1,cow+n+1,cmp);//排序
dfs(1,0); //深搜
if(ansa==-1)
{
cout<<"Mark is too tall";//无解
}
else
{
cout<<ansa;
}
return 0;
}