首先将纵坐标离散化。 将所有点按照横坐标排序,枚举矩形的上边界,然后往后依次加入每个点,这样就确定了 矩形的上下边界。设 v[y] 表示矩形内部纵坐标为 y 的点的权值和,则答案为 v 的最大子段和, 用线段树维护带修改的最大子段和即可。 时间复杂度 O(nlogn)。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
#include<string>
#include<vector>
#include<set>
#include<bitset>
#include<algorithm>
using namespace std;
#define ll long long
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ull unsigned long long
#define endl '\n'
#define clr_0(a) memset(a, 0, sizeof(a))
#define clr_INF(a) memset(a, INF, sizeof(a))
#define lowbit(x) x & -x
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define PB push_back
#define POP pop_back
const double pi = acos(-1);
const int maxn = 2000 + 10;
const int maxm = (maxn<<5) + 5;
const ll mod = 998244353;
const int hash_mod = 19260817;
int T, n, cnt_b;
ll suml[maxn<<2], sumr[maxn<<2], sum[maxn<<2], mx[maxn<<2];
int b[maxn];
struct node{
int x, y, z;
friend bool operator < (const node& A, const node& B){
return A.x < B.x;
}
}p[maxn];
void pushup(int rt){
suml[rt] = max(suml[rt<<1], sum[rt<<1] + suml[rt<<1|1]);
sumr[rt] = max(sumr[rt<<1|1], sum[rt<<1|1] + sumr[rt<<1]);
sum[rt] = sum[rt<<1] + sum[rt<<1|1];
mx[rt] = max(max(mx[rt<<1], mx[rt<<1|1]), sumr[rt<<1] + suml[rt<<1|1]);
}
void build(int rt, int l, int r){
suml[rt] = sumr[rt] = sum[rt] = mx[rt] = 0;
if(l == r) return;
int mid = (l + r) >> 1;
if(l <= mid) build(lson);
if(r > mid) build(rson);
}
void update(int rt, int l, int r, int x, int val){
if(l == r){
suml[rt] = sumr[rt] = sum[rt] = (mx[rt] += val);
return;
}
int mid = (l + r) >> 1;
if(x <= mid) update(lson, x, val);
if(x > mid) update(rson, x, val);
pushup(rt);
}
int main()
{
//freopen("E://1005.in","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
//freopen("E://outt.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
scanf("%d", &T);
while(T --){
scanf("%d", &n);
cnt_b = 0;
for(int i = 1 ; i <= n ; ++ i){
scanf("%d %d %d", &p[i].x, &p[i].y, &p[i].z);
b[++cnt_b] = p[i].y;
}
sort(b + 1, b + 1 + cnt_b);
int m = unique(b + 1, b + 1 + cnt_b) - b - 1;
sort(p + 1, p + 1 + n);
ll ans = -1e18;
for(int i = 1 ; i <= n ; ++ i) p[i].y = lower_bound(b + 1, b + 1 + m, p[i].y) - b;
for(int i = 1 ; i <= n ; ++ i){
if(i != 1 && p[i].x == p[i-1].x) continue;
build(1, 1, m);
int k;
for(int j = i ; j <= n ; j = k){
for(k = j ; k <= n && p[k].x == p[j].x ; ++ k) update(1, 1, m, p[k].y, p[k].z);
ans = max(ans, mx[1]);
}
}
cout << ans << endl;
}
return 0;
}