题目链接
题目梗概
有一片花生田,每个点都有花生苗,但只有几个花生苗下有花生,现有一人,他在路边(第0行),在可以在路边任意选择一列进入花生田进行采摘,每走一步花费一秒,采摘花生花费一秒,问在给定的时间内,他可以采摘多少花生。(必须按照花生的多少降序采摘)。
解题思路
花生的采摘顺序已经定下来,剩下的问题就只有时间的问题了。
对于将要采摘的下一个花生,如果采摘完后的时间还能后支持回到路边,就采摘该花生,如果不支持,则不采摘,直接回到路边,不再采摘。
完整代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct point{
int row, col, corn;
}p;
bool cmp(point a, point b){
return a.corn > b.corn;
}
int main(){
int m, n, k;
cin >> m >> n >> k;
int tmp;
vector<point> d;
for(int i = 1;i <= m;++i){
for(int j = 1;j <= n;++j){
cin >> tmp;
if(tmp > 0){
p.row = i;
p.col = j;
p.corn = tmp;
d.push_back(p);
}
}
}
sort(d.begin(),d.end(),cmp);
int ans = 0, lstC = d[0].col, lstR = 0, dis;
for(int i = 0;i<d.size();++i){
dis = abs(d[i].col - lstC) + abs(d[i].row - lstR) + 1;
if(dis + d[i].row> k) break;
else{
ans += d[i].corn;
k -= dis;
lstC = d[i].col;
lstR = d[i].row;
}
}
cout << ans;
return 0;
}