排序。
依次判断。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 50;
struct Point
{
int v;
int r, c;
Point(int v=0, int r=0, int c=0)
{
this->v = v;
this->r = r;
this->c = c;
}
};
Point point[N*N+2];
int map[N+2][N+2];
bool _cmp(Point x, Point y)
{
return x.v > y.v;
}
int time_count(int r, int c, int i)
{
return abs(point[i].r-r) + abs(point[i].c-c) + 1 + point[i].r;
}
void _pick(int &ans, int n, int limit)
{
int cur_time = 0;
int cur_r = 0;
int cur_c = point[0].c;
ans = 0;
for (int i = 0; i < n; i++)
{
int t = time_count(cur_r, cur_c, i);
if (cur_time + t <= limit)
{
ans += point[i].v;
cur_time += t - point[i].r;
cur_r = point[i].r;
cur_c = point[i].c;
}
else break;
}
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
// ini
memset(map, 0, sizeof(map));
memset(point, 0, sizeof(point));
// input
int n, m;
int limit;
int cnt = 0;
scanf("%d%d%d", &n, &m, &limit);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d", &map[i][j]);
if (map[i][j] > 0) point[cnt++] = Point(map[i][j], i, j);
}
// work
sort(point, point+cnt, _cmp);
int ans;
_pick(ans, cnt, limit);
// print
printf("%d\n", ans);
}
return 0;
}