智能除草农业植保无人机作为最新的设备,可以加注除草剂进行除草。每次工作可以喷洒边长为K的正方形区域。现有一块边长为N的正方形农田,将其分成N*N个方格单元,已知每个单元里的杂草数量。求该植保无人机一次工作最多除草量和最少除草量的差值。输入说明:第一行是2个正整数,分别为N和K(1≤K≤N≤1000)。之后N行N列正整数,表示每个单元中的杂草数量(不超过50)。输出说明:该植保无人机一次工作最多除草量和最少除草量的差值。
输入样例:
5 2
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 2 3 1 1
输出样例:
7 4
代码:
C++:
#include<iostream>
using namespace std;
int main() {
int n, k; cin >> n >> k;
int arr[500][500];
for (auto i = 0; i < n; i++) {
for (auto j = 0; j < n; j++) {
int num;
cin >> num;
arr[i][j] = num;
}
}
int max = 0;
int min = 0x3f3f3f3f;
for (auto i = 0; i < n - (k - 1); i++) {
for (auto j = 0; j < n - (k - 1); j++) {
int sum = 0;
for (int i1 = 0; i1 < k; i1++) {
for (int j1 = 0; j1 < k; j1++) {
sum += arr[i + i1][j + j1];
}
}
if (max <= sum) {
max = sum;
}
if (min >= sum) {
min = sum;
}
}
}
cout << max << ' ' << min << endl;
return 0;
}
Python:
n, k = map(int, input().split())
arr = [[0 for j in range(500)] for i in range(500)]
maxNum = 0
minNum = 0x3f3f3f3f
for i in range(n):
count = 0
num = map(int, input().split())
for j in num:
arr[i][count] = j
count += 1
for i in range(0, n - (k - 1), 1):
for j in range(0, n - (k - 1), 1):
s = 0
for x in range(k):
for y in range(k):
s += arr[i + x][j + y]
if maxNum <= s:
maxNum = s
if minNum >= s:
minNum = s
print(str(maxNum) + " " + str(minNum))
Java:
package com.my.gududu;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, k;
n = input.nextInt();
k = input.nextInt();
int arr[][] = new int[500][500];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num;
num = input.nextInt();
arr[i][j] = num;
}
}
int max = 0;
int min = 0x3f3f3f3f;
for (int i = 0; i < n - (k - 1); i++) {
for (int j = 0; j < n - (k - 1); j++) {
int sum = 0;
for (int i1 = 0; i1 < k; i1++) {
for (int j1 = 0; j1 < k; j1++) {
sum += arr[i + i1][j + j1];
}
}
if (max <= sum) {
max = sum;
}
if (min >= sum) {
min = sum;
}
}
}
System.out.println(max + " " + min);
}
}