跳到正文

个人记录

U571432最大连续字段和

clo201111约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年6月14日
收录
2025年12月12日
更新
2026年9月3日
篇幅
约 3 分钟

版本

  1. v1当前

最大连续字段和

cpp11
#include<bits/stdc++.h>
#define mid ((l+r)>>1)
using namespace std;
struct node {
  int sum,l,r,max;
  int operator=(int x) {
    return this->sum=this->l=this->r=this->max=x;
  }
};
int n,m,k,l,r,idx,x;
int a[500005];
node tree[5000005];
node add(node a,node b) {
  node c;
  c.sum=a.sum+b.sum;
  c.l=max(a.l,a.sum+b.l);
  c.r=max(b.r,b.sum+a.r);
  c.max=max(max(a.max,b.max),a.r+b.l);
  return c;
}
void build_tree(int k,int l,int r) {
  if(l==r) {
    tree[k]=a[l];
    return;
  }
  build_tree(k*2,l,mid);
  build_tree(k*2|1,mid+1,r);
  tree[k]=add(tree[k*2],tree[k*2|1]);
}
void change(int k,int l,int r,int x,int v) {
  if(l==r) {
    tree[k]=v;
    return;
  }
  if(x<=mid)
    change(k*2,l,mid,x,v);
  else
    change(k*2|1,mid+1,r,x,v);
  tree[k]=add(tree[k*2],tree[k*2|1]); 
}
node ask(int k,int l,int r,int x,int y) {
  if(x<=l && r<=y)  return tree[k];
  if(y<=mid)  return ask(k*2,l,mid,x,y);
  if(x>mid)  return ask(k*2|1,mid+1,r,x,y);
  node c=add(ask(k*2,l,mid,x,y),ask(k*2|1,mid+1,r,x,y));
  return c;
}
int main() {
  scanf("%d",&n); scanf("%d",&m);
  for(int i=1;i<=n;i++)
    scanf("%d",a+i);
  build_tree(1,1,n);
  for(int i=1;i<=m;i++) {
    scanf("%d",&k);
    switch(k) {
    case 1:
      scanf("%d",&l); scanf("%d",&r);
      if(l>r)  swap(l,r);
      printf("%d\n",ask(1,1,n,l,r).max);
      break;
    case 2:
      scanf("%d",&idx); scanf("%d",&x);
      change(1,1,n,idx,x);
	}
  }
}

原文