题目:http://acm.hdu.edu.cn/showproblem.php?pid=6638
题意:给n个点的坐标和权值,求最大权值和矩阵。
思路:n<=2000,每次枚举上下边界,每次向线段树中加点,线段树维护上下边界内的最大子段和即可,要注意移动上边界时可能会有多个点在当前直线上,同样的,移动下边界时要把边界上的所有点都更新后才能更新ans。
线段树维护区间最大子段和:小白逛公园 : 题解
#include
#define LL long long
#define ls rt<<1
#define rs rt<<1|1
using namespace std;
const int maxn = 1e5+5;
vectorvecx, vecy;
int getidx(int x){return lower_bound(vecx.begin(), vecx.end(), x)-vecx.begin()+1;}
int getidy(int x){return lower_bound(vecy.begin(), vecy.end(), x)-vecy.begin()+1;}
struct T{ LL sum, lm, rm, mm;}t[maxn<<2];
struct P{ int x, y; LL val;}p[maxn];
bool cmp( P a, P b){return a.y == b.y ? a.x < b.x : a.y > b.y;}
int Case, n, len;
void pushup(int rt){
t[rt].sum = t[ls].sum + t[rs].sum;
t[rt].lm = max(t[ls].lm, t[ls].sum+t[rs].lm);
t[rt].rm = max(t[rs].rm, t[rs].sum+t[ls].rm);
t[rt].mm = max(max(t[ls].mm, t[rs].mm), t[ls].rm+t[rs].lm);
}
void build(int rt, int l, int r){
t[rt].lm = t[rt].rm = t[rt].mm = t[rt].sum = 0;
if(l == r) return ;
int mid = l+r >> 1;
build(ls, l, mid); build(rs, mid+1, r);
pushup(rt);
}
void update(int rt, int l, int r, int pos, LL val){
if(l == r) {
t[rt].lm = t[rt].rm = t[rt].mm = t[rt].sum = t[rt].sum + val;
return ;
}
int mid = l+r >> 1;
if(pos <= mid) update(ls, l, mid, pos, val);
else update(rs, mid+1, r, pos, val);
pushup(rt);
}
int main()
{
scanf("%d", &Case);
while(Case--){
vecx.clear(); vecy.clear();
scanf("%d", &n);
int x, y;
for(int i=1; i<=n; i++){
scanf("%d%d%lld", &p[i].x, &p[i].y, &p[i].val);
vecx.push_back(p[i].x); vecy.push_back(p[i].y);
}
sort(vecx.begin(), vecx.end()); vecx.erase(unique(vecx.begin(), vecx.end()), vecx.end()); len = vecx.size();
sort(vecy.begin(), vecy.end()); vecy.erase(unique(vecy.begin(), vecy.end()), vecy.end());
for(int i=1; i<=n; i++) p[i].x = getidx(p[i].x), p[i].y = getidy(p[i].y);
sort(p+1, p+n+1, cmp);
LL ans = -1e18; int last = -1;
for(int i=1; i<=n; i++){
if(p[i].y == last) continue;
build(1, 1, len);
int k;
for(int j=i; j<=n; j=k){
for(k=j; k<=n&&p[k].y==p[j].y; k++) update(1, 1, len, p[k].x, p[k].val);
ans = max(ans, t[1].mm);
} last = p[i].y;
}
cout << ans << endl;
}
}