There are nn pirate chests buried in Byteland, labeled by 1,2,…,n1,2,…,n. The ii-th chest's location is (xi,yi)(xi,yi), and its value is wiwi, wiwi can be negative since the pirate can add some poisonous gases into the chest. When you open the ii-th pirate chest, you will get wiwi value.
You want to make money from these pirate chests. You can select a rectangle, the sides of which are all paralleled to the axes, and then all the chests inside it or on its border will be opened. Note that you must open all the chests within that range regardless of their values are positive or negative. But you can choose a rectangle with nothing in it to get a zero sum.
Please write a program to find the best rectangle with maximum total value.
Input
The first line of the input contains an integer T(1≤T≤100)T(1≤T≤100), denoting the number of test cases.
In each test case, there is one integer n(1≤n≤2000)n(1≤n≤2000) in the first line, denoting the number of pirate chests.
For the next nn lines, each line contains three integers xi,yi,wi(−109≤xi,yi,wi≤109)xi,yi,wi(−109≤xi,yi,wi≤109), denoting each pirate chest.
It is guaranteed that ∑n≤10000∑n≤10000.
Output
For each test case, print a single line containing an integer, denoting the maximum total value.
Sample Input
2 4 1 1 50 2 1 50 1 2 50 2 2 -500 2 -1 1 5 -1 1 1
Sample Output
100 6
将X从小到大排序,将Y左边离散化,然后枚举x的上下界,然后“顺路”建立线段树维护最大连续区间和即可。
这个题最主要的就是建立线段树维护最大连续区间和这个操作,把原来N^3的枚举操作优化成N^2logn的复杂度。看不明白的直接下方留言就好惹~。
#include
using namespace std;
int soty[2005];
#define LL long long
#define ls p<<1
#define rs p<<1|1
struct fuck { int x, y, w; }sp[2002];
bool cmp(fuck a, fuck b) {
return a.x < b.x;
}
int cnty;
int idy(int x) { return lower_bound(soty + 1, soty + cnty + 1, x) - soty; }
struct ed {
LL ll, lr, lm, sum;
}tree[2003 * 3];
inline void up(int p) {
tree[p].sum = tree[ls].sum + tree[rs].sum;
tree[p].ll = max(tree[ls].ll, tree[ls].sum + tree[rs].ll);
tree[p].lr = max(tree[rs].lr, tree[rs].sum + tree[ls].lr);
tree[p].lm = max(tree[ls].lr + tree[rs].ll, max(tree[ls].lm, tree[rs].lm));
}
void add(int l, int r, int p, int pos, LL x) {
if (l == r) {
tree[p].lm += x;
tree[p].sum = tree[p].ll = tree[p].lr = tree[p].lm;
return;
}
int mid = (l + r) >> 1;
if (pos <= mid)add(l, mid, ls, pos, x);
else add(mid + 1, r, rs, pos, x);
up(p);
}
long long dp[2005];
int main() {
int te;
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> te;
while (te--) {
int n; cin >> n;
cnty = 0;
for (int i = 1; i <= n; i++) {
cin >> sp[i].x >> sp[i].y >> sp[i].w;
soty[++cnty] = sp[i].y;
}
sort(sp + 1, sp + 1 + n, cmp);
sort(soty + 1, soty + 1 + cnty);
cnty = unique(soty + 1, soty + 1 + cnty) - soty - 1;
long long ans = 0;
for (int i = 1; i <= n; i++) {
if (i != 1 && sp[i].x == sp[i - 1].x)continue;
memset(tree, 0, sizeof tree);
for (int j = i; j <= n; j++) {
add(1, cnty, 1, idy(sp[j].y), sp[j].w);
if (j == n || sp[j].x != sp[j + 1].x) {
//cout << i << " " << j << "\n";
ans = max(ans, tree[1].lm);
}
}
}
cout << ans << "\n";
}
return 0;
}