题目:https://www.nowcoder.com/pat/2/problem/249
1 #include <iostream> 2 #include <algorithm> 3 #include <cmath> 4 using namespace std; 5 const int maxn = 10005; 6 struct node{ 7 int x, y; 8 int v; 9 }a[maxn]; 10 11 bool cmp(node z, node b){ 12 return z.v > b.v; 13 } 14 15 int main(){ 16 std::ios::sync_with_stdio(false); 17 int m, n, k, v; 18 while (cin >> m >> n >> k){ 19 int len = 0; 20 for (int i = 1; i <= m; i++){ 21 for (int j = 1; j <= n; j++){ 22 cin >> v; 23 if (v == 0) 24 continue; 25 a[len].v = v; 26 a[len].x = i; 27 a[len].y = j; 28 len++; 29 } 30 } 31 sort(a, a + len, cmp); 32 int ans = 0; 33 int time = 0; 34 bool ok = 1; 35 for (int i = 0; i < len; i++){ 36 if (ok){ 37 ok = 0; 38 if (time + a[i].x + 1 + a[i].x > k) 39 break; 40 else{ 41 ans += a[i].v; 42 time += a[i].x+ 1; 43 } 44 } 45 else{ 46 int sum = abs(a[i].x - a[i - 1].x) + abs(a[i].y - a[i - 1].y); 47 if (time + sum + 1 + a[i].x > k) 48 break; 49 else{ 50 ans += a[i].v; 51 time += sum + 1; 52 } 53 } 54 } 55 cout << ans << endl; 56 } 57 //system("pause"); 58 return 0; 59 }