题解:AT_abc462_d [ABC462D] Accomplice

· · 题解

笑点解析:树状数组。

形式化题意:

ans=\sum_{i=1}^{n}\sum_{j=1}^{i-1} \min\{t_i,t_j\}-\max\{s_i,s_j\}+1-d

(可以只枚举 j<i 的是因为题目说两名凶手的顺序不计)

不妨考虑按 s_i 从小到大排序,然后只枚举 i,那么我们就拆掉了 \max\{s_i,s_j\}=s_i 然后不妨设 S=s_i+d-1,式子变为:

ans_i=\sum_{j=1}^{i-1} \min\{t_i,t_j\}-S

考虑分类讨论 t_j 的情况:

不难注意到小于 t_i 大于等于 t_i 的个数都可以用权值树状数组来统计,同样的,小于 t_i 的 t_j 的和也同样可以。

:::success[Ac Code]

#include <bits/stdc++.h>
using namespace std;
#ifdef __linux__
#define gc getchar_unlocked
#define pc putchar_unlocked
#else
#define gc _getchar_nolock
#define pc _putchar_nolock
#endif
#define int long long
#define rint register int
#define _ read<int>()
template<class T>inline T read()
{
    T r=0,f=1;char c=gc();
    while(!isdigit(c))
    {
        if(c=='-') f=-1;
        c=gc();
    }
    while(isdigit(c)) r=(r<<1)+(r<<3)+(c^48),c=gc();
    return f*r;
}
inline void out(rint x)
{
    if(x<0) pc('-'),x=-x;
    if(x<10) pc(x+'0');
    else out(x/10),pc(x%10+'0');
}
const int N=2e5+10,M=1e6+10;
struct oi
{
    int s,t;
}a[N];
inline int lowbit(rint x) {return x&(-x);}
struct BIT
{
    int tr[M];
    inline void modify(rint p,rint v)
    {
        while(p<M)
        {
            tr[p]+=v;
            p+=lowbit(p);
        }
    }
    inline int query(rint p)
    {
        if(!p) return 0;
        rint ans=0;
        while(p)
        {
            ans+=tr[p];
            p-=lowbit(p);
        }
        return ans;
    }
    inline int query1(rint l,rint r)
    {
        return query(r)-query(l-1);
    }
}cnt,s;
inline bool cmp(const oi &x,const oi &y)
{
    if(x.s!=y.s) return x.s<y.s;
    return  x.t<y.t;
}
signed main()
{
    rint n=_,d=_; 
    for(rint i=1;i<=n;++i)
    {
        a[i]={_,_};
    }     
    sort(a+1,a+n+1,cmp);
    rint ans=0;
    for(rint i=1;i<=n;++i)
    {
        rint L=d+a[i].s-1;
        if(a[i].t<L) continue;
        //t[j]>=t[i] min(t[i],t[j])=t[i]
        rint cnt1=cnt.query1(a[i].t,M-1);
        ans+=(a[i].t*cnt1-L*cnt1);
        //t[j]<t[i] min(t[i],t[j])=t[j]
        rint cnt2=cnt.query1(L+1,a[i].t-1),s2=s.query1(L+1,a[i].t-1);
        ans+=(s2-L*cnt2);
        cnt.modify(a[i].t,1);
        s.modify(a[i].t,a[i].t);
    }
    out(ans);
    return 0;
}

:::