李超线段树(2024.8.16)

· · 个人记录

李超线段树(2024.8.16)

题目

在平面直角坐标系 xOy 上进行 q 次操作:

数据范围:1\le n,x_A,x_B\le 10^5,1\le y_A,y_B\le 10^9。

算法

线段树维护 x 坐标中对于一个区间中点的最优线段,可以作为懒标记。每次加一条线段时求出其所在直线的斜率 k 与截距 b,用于求出 x 为一给定值时的 y。在线段树上的一个区间 [l,r] 更新信息时,首先更新当前区间中点 mid=\frac{l+r}{2} 的最优线段。若原来的线段比新的线段更优,分类讨论:

查询答案时,求路径上所有最优线段在 x=x_q 时的 y_{\max}。

时间复杂度 O(q\log x_{\max})。

代码

#include<bits/stdc++.h>
using namespace std;
#define mid (l+r)/2
const int mod1=39989;
const int mod2=1e9;
const double t=1e-9;
const int N=1e5+5;
int q,ans,cnt,num[4*N];
double k[N],b[N];
double f(int idx,int x){
    return k[idx]*x+b[idx];
}
double cmp(double x,double y){
    if(x-y>t) return 1;
    if(y-x>t) return -1;
    return 0;
}
void add(int xa,int ya,int xb,int yb){
    cnt++;
    if(xa==ya) k[cnt]=0,b[cnt]=max(ya,yb);
    else k[cnt]=1.0*(yb-ya)/(xb-xa),b[cnt]=ya-k[cnt]*xa;
}
void upd(int p,int l,int r,int x){
    int &y=num[p];
    int flag=cmp(f(x,mid),f(y,mid));
    if(flag==1||(!flag&&x<y)) swap(x,y);
    int yl=cmp(f(x,l),f(y,l)),yr=cmp(f(x,r),f(y,r));
    if(yl==1||(!yl&&x<y)) upd(2*p,l,mid,x);
    if(yr==1||(!yr&&x<y)) upd(2*p+1,mid+1,r,x);
}
void update(int p,int L,int R,int l,int r,int x){
    if(L<=l&&r<=R) upd(p,l,r,x);
    else{
        if(mid>=L) update(2*p,L,R,l,mid,x);
        if(mid<R) update(2*p+1,L,R,mid+1,r,x);
    }
}
pair<double,int> g(pair<double,int> x,pair<double,int> y){
    if(cmp(x.first,y.first)==1) return x;
    if(cmp(y.first,x.first)==1) return y;
    if(x.second<y.second) return x;
    return y;
}
pair<double,int> query(int p,int l,int r,int x){
    if(x<l||x>r) return {0,0};
    double ymax=f(num[p],x);
    if(l==r) return {ymax,num[p]};
    return g({ymax,num[p]},g(query(2*p,l,mid,x),query(2*p+1,mid+1,r,x)));
}
int main(){
    cin>>q;
    while(q--){
        int opt;cin>>opt;
        if(!opt){
            int x;cin>>x;
            x=((x+ans-1)%mod1+mod1)%mod1+1;
            ans=query(1,1,mod1,x).second;
            cout<<ans<<"\n";
        }
        else{
            int xa,ya,xb,yb;cin>>xa>>ya>>xb>>yb;
            xa=((xa+ans-1)%mod1+mod1)%mod1+1,ya=((ya+ans-1)%mod2+mod2)%mod2+1;
            xb=((xb+ans-1)%mod1+mod1)%mod1+1,yb=((yb+ans-1)%mod2+mod2)%mod2+1;
            if(xa>xb) swap(xa,xb),swap(ya,yb);
            add(xa,ya,xb,yb);
            update(1,xa,xb,1,mod1,cnt);
        }
    }
    return 0;
}