HDU 5306 Gorgeous Sequence(線段樹)
阿新 • • 發佈:2019-01-09
1和2都是常見操作,就是這個0操作很難搞定。參考了吉如一論文。感覺非常的強。
區間的max可以看做是區間標記,我們可以維護3個值,區間最大值,區間次大值,區間最大值的個數。然後我們每次做0操作的時候,就會有3種情況。
把t作為要更新的值。
1:t>=區間最大值,那麼就是無效操作。
2:區間次大值 < t <區間最大值,因為我們已經求得了最大值的個數,所以我們可以直接更新這段的sum。
3:其他情況。繼續搜下去,直到搜到前兩種情況為止。
然後我們可以把區間的最大值看做是這個區間的標記,因為每次更新的時候只會更新到(區間次大值 < t < 區間最大值)的情況,而且因為沒有加法操作,所以max從上到下一定是非遞增的,那麼我們在更新的時候就可以從每次pushdown的時候判斷一下子節點和當前節點的最大值的情況,然後更新一下子節點的sum和max值。複雜度證明並不會,但是論文裡說是O(mlogn)的。
2000+ms AC
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define pb push_back
#define mp make_pair
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define calm (l+r)>>1
const int INF = 2139062143;
const int maxn=1000010;
int n,m;
struct Seg{
ll sum[maxn<<2 ];
int mx[maxn<<2],mxnum[maxn<<2],sc[maxn<<2];
inline void pushup(int rt){
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
mx[rt]=max(mx[rt<<1],mx[rt<<1|1]);
mxnum[rt]=0;
sc[rt]=max(sc[rt<<1],sc[rt<<1|1]);
if(mx[rt]==mx[rt<<1])mxnum[rt]+=mxnum[rt<<1];
else sc[rt]=max(sc[rt],mx[rt<<1]);
if(mx[rt]==mx[rt<<1|1])mxnum[rt]+=mxnum[rt<<1|1];
else sc[rt]=max(sc[rt],mx[rt<<1|1]);
}
inline void pushdown(int rt){
if(mx[rt]<mx[rt<<1]){
sum[rt<<1]-=(ll)mxnum[rt<<1]*(mx[rt<<1]-mx[rt]);
mx[rt<<1]=mx[rt];
}
if(mx[rt]<mx[rt<<1|1]){
sum[rt<<1|1]-=(ll)mxnum[rt<<1|1]*(mx[rt<<1|1]-mx[rt]);
mx[rt<<1|1]=mx[rt];
}
}
void build(int l,int r,int rt){
if(l==r){
scanf("%I64d",&sum[rt]);
mx[rt]=sum[rt];
mxnum[rt]=1;
sc[rt]=-1;
return;
}
int m=calm;
build(lson);build(rson);
pushup(rt);
}
void update(int L,int R,int v,int l,int r,int rt){
if(v>=mx[rt])return;
if(L<=l&&r<=R&&sc[rt]<v){
sum[rt]-=(ll)mxnum[rt]*(mx[rt]-v);
mx[rt]=v;
return;
}
pushdown(rt);
int m=calm;
if(L<=m)update(L,R,v,lson);
if(R>m)update(L,R,v,rson);
pushup(rt);
}
int getMax(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return mx[rt];
}
pushdown(rt);
int m=calm,ans=0;
if(L<=m)ans=getMax(L,R,lson);
if(R>m)ans=max(ans,getMax(L,R,rson));
return ans;
}
ll query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return sum[rt];
}
pushdown(rt);
int m=calm;
ll ans=0;
if(L<=m)ans+=query(L,R,lson);
if(R>m)ans+=query(L,R,rson);
return ans;
}
}tree;
int main(){
//freopen("D://input.txt","r",stdin);
int T;scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
tree.build(1,n,1);
while(m--){
int op,l,r;
scanf("%d%d%d",&op,&l,&r);
if(op==0){
int x;scanf("%d",&x);
tree.update(l,r,x,1,n,1);
}
else if(op==1){
printf("%d\n",tree.getMax(l,r,1,n,1));
}
else{
printf("%I64d\n",tree.query(l,r,1,n,1));
}
}
}
return 0;
}