因为数据只有5000,所以可以O(n2)暴力。
首先预处理二维前缀和,然后枚举正方形的左上角,将每一次的得到的总价值去最大,作为答案。
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<cstdlib> 7 #include<vector> 8 #include<queue> 9 #include<stack> 10 #include<cctype> 11 using namespace std; 12 #define enter puts("") 13 #define space putchar(' ') 14 #define Mem(a) memset(a, 0, sizeof(a)) 15 typedef long long ll; 16 typedef double db; 17 const int INF = 0x3f3f3f3f; 18 const db eps = 1e-8; 19 const int maxn = 5e3 + 1; 20 inline ll read() 21 { 22 ll ans = 0; 23 char ch = getchar(), last = ' '; 24 while(!isdigit(ch)) {last = ch; ch = getchar();} 25 while(isdigit(ch)) {ans = ans * 10 + ch - '0'; ch = getchar();} 26 if(last == '-') ans = -ans; 27 return ans; 28 } 29 inline void write(ll x) 30 { 31 if(x < 0) putchar('-'), x = -x; 32 if(x >= 10) write(x / 10); 33 putchar(x % 10 + '0'); 34 } 35 36 int n, r; 37 int sum[maxn + 5][maxn + 5], ans = 0; 38 39 int main() 40 { 41 n = read(); r = read(); 42 for(int i = 1; i <= n; ++i) sum[read() + 1][read() + 1] = read(); //这个操作有点秀 43 for(int i = 1; i <= maxn; ++i) 44 for(int j = 1; j <= maxn; ++j) sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + sum[i][j]; 45 for(int i = 1; i <= maxn - r + 1; ++i) 46 for(int j = 1; j <= maxn - r + 1; ++j) 47 ans = max(ans, sum[i + r - 1][j + r - 1] - sum[i + r - 1][j - 1] - sum[i - 1][j + r - 1] + sum[i - 1][j - 1]); 48 write(ans); enter; 49 return 0; 50 }