题解 CF915E 【Physical Education Lessons】

· · 题解

最近在学ODT,讲一下这题ODT解法。

不会ODT?

这题就是一道ODT的板子,操作是推平,查询是求和

Q:这题不保证数据随机为什么还能用ODT?

A:hackODT的方法是没有推平操作,但这题修改操作全是推平操作。

于是暴力很好写,但CF的毒瘤们不会让你过的,故考虑优化。

每次查询区间是一定的,所以就维护一个变量 sum 表示 1 \rightarrow n 的和,再推平时统计,推平区间里有多少个元素值会变化,再根据变成什么修改 sum

code:

#include<bits/stdc++.h>
#define SIT set<node>::iterator
using namespace std;
int read()
{
    register int x=0,f=1;register char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
struct node
{
    int l,r;
    mutable long long v;
    node(int L, int R=-1, long long V=0):l(L), r(R), v(V) {}
    bool operator<(const node& o) const{return l < o.l;}
};
set<node>odt;
long long sum;
SIT spilt(int mid)
{
    SIT it=odt.lower_bound(node(mid));
    if(it!=odt.end()&&it->l==mid) return it;
    it--;
    node temp=*it;
    odt.erase(it);
    odt.insert(node(temp.l,mid-1,temp.v));
    return odt.insert(node(mid,temp.r,temp.v)).first;
}
void assign(int l,int r,long long val)
{
    SIT it2=spilt(r+1),it1=spilt(l);
    long long res=0;
    for(SIT it=it1;it!=it2;it++)
    {
        if(it->v!=val)res+=it->r-it->l+1;//一共有多少值会变
    }
    odt.erase(it1,it2);
    odt.insert(node(l,r,val));
    sum+=((val==0)?-res:res);//是加还是减
}
int n,q;
int main()
{
    n=read();q=read();
    odt.insert(node(1,n,1));
    sum=n;
    for(int i=1;i<=q;i++)
    {
        int l=read(),r=read();
        short opt=read();
        if(opt==1)
        {
            assign(l,r,0);
            printf("%d\n",sum);
        }
        else
        {
            assign(l,r,1);
            printf("%d\n",sum);
        }
    }
    return 0;
}
\text{That~is~all.~Thanks~fo~reading.}

↓点个赞吧