上课记录-来追梦-10.20树状数组

· · 个人记录

上课题目记录

来追梦 | 10.20树状数组

T2:P3368 【模板】树状数组 2

代码

::::success[AC code]

#include<bits/stdc++.h>
using namespace std;
int n,m,a[500010],c[500010];
int lowbit(int x)
{
    return x&-x;
}
int q(int x)
{
    int cnt=0;
    while(x!=0)
    {
        cnt+=c[x];
        x-=lowbit(x);
    }
    return cnt;
}
void u(int x,int y)
{
    while(x<=n)
    {
        c[x]+=y;
        x+=lowbit(x);
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        u(i,a[i]-a[i-1]);
    }
    while(m--)
    {
        int op;
        cin>>op;
        if(op==1)
        {
            int x,y,z;
            cin>>x>>y>>z;
            u(x,z);
            u(y+1,-z);
        }
        else
        {
            int x;
            cin>>x;
            cout<<q(x)<<endl;
        }
    }
    return 0;
}

::::

赛后题解

和上一道题相当于反过来了,就可以使用差分,区间加减对端点操作,求某个点的值用前缀和就行了。

复杂度

  • 时间复杂度:O((n+m)\log n)

    T3:P5149 会议座位

代码

::::success[AC code]

#include<bits/stdc++.h>
using namespace std;
long long n,c[100010],ans;
map<string,long long> mp;
long long lowbit(long long x)
{
    return x&-x;
}
long long q(long long x)
{
    long long cnt=0;
    while(x!=0)
    {
        cnt+=c[x];
        x-=lowbit(x);
    }
    return cnt;
}
void u(long long x,long long y)
{
    while(x<=n)
    {
        c[x]+=y;
        x+=lowbit(x);
    }
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        string s;
        cin>>s;
        mp[s]=i;
    }
    for(int i=1;i<=n;i++)
    {
        string s;
        cin>>s;
        ans+=i-1-q(mp[s]);
        u(mp[s],1);
    }
    cout<<ans<<endl;
    return 0;
}

::::

赛后题解

这个就是求逆序对,先记录下每个字符的位置,然后拿一个虚拟数轴,按照其中一维,每次加进去,比它之前加进去的时间早,那一维也更小,另一维更大的就是答案,每次加上就行了。

复杂度

  • 时间复杂度:O(n\log n)

    课后作业

  • P5149 会议座位
  • U125682 [ybt1536]数星星
  • P3531 [POI 2012] LIT-Letters

    ::::align{right}

    2026年10月20日

    ::::