这道题我用来练习二维树状数组
把一维变成二维思路也很简单,代码不麻烦
关键是计算区间和时要注意正方形边界是否包含,是否-1
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
inline int lowbit(int x)
{
return (x & (-x));
}
using namespace std;
int d, n,x,y,k;
int tree[130][130];
inline int read()
{
int x = 0, y = 1; char c = getchar();
while (c>'9' || c<'0'){ if (c == '0')y = -1; c = getchar(); }
while (c >= '0'&&c <= '9'){ x = x * 10 + c - '0'; c = getchar(); }
return x*y;
}
void add(int x, int y, int k)
{
for (int i = x; i <= 129; i += lowbit(i))
{
for (int j = y; j <= 129; j += lowbit(j))
{
tree[i][j] += k;
}
}
}
int query(int x, int y)
{
int ans = 0;
for (int i = x; i >= 1; i -= lowbit(i))
{
for (int j = y; j >= 1; j -= lowbit(j))
{
ans += tree[i][j];
}
}
return ans;
}
int main()
{
d = read();
n = read();
for (int i = 0; i < n; ++i)
{
x = read();
y = read();
k = read();
add(x+1, y+1, k);
}
int maxcount = 0;
int anscount = 0;
for (int i = 1; i <= 129 ; ++i)
{
for (int j = 1; j <= 129 ; ++j)
{
int x2 = i + d;
if (x2 > 129)x2 = 129;
int y2 = j + d;
if (y2 > 129)y2 = 129;
int x1 = i - d;
if (x1<1)x1 = 1;
int y1 = j - d;
if (y1 <1)y1 = 1;
int count = query(x2, y2) - query(x2,y1-1)
- query(x1-1,y2) + query(x1-1,y1-1);//注意边界
if (count > maxcount)
{
maxcount = count;
anscount = 1;
}
else if (count == maxcount)
{
anscount++;
}
}
}
cout << anscount <<" " << maxcount;
return 0;
}