树状数组求逆序对-洛谷P3531 [POI2012]LIT-Letters

https://daniu.luogu.org/problem/show?pid=3531
我们把A串标个号;
然后在B串里按A串的标号求一下逆序对就好了;
对于重复的字母;
A串里直接靠前的标号小
B串也一样;
这样显然正确;

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define Ll long long
using namespace std;
struct cs{
    Ll nxt;
}a[1000005];
Ll f[1000005];
Ll head[100],ll,now[100];
Ll n,ans,k,kk;
char c;
Ll out(Ll k){
    Ll ans=0;
    for(Ll i=k;i>=1;i-=i&-i)ans+=f[i];
    return ans;
}
Ll add(Ll k){
    for(Ll i=k;i<=n;i+=i&-i)f[i]++;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n;
    for(Ll i=1;i<=n;i++){
        cin>>c;
        k=c;
        if(now[k]==0)head[k]=i;else a[now[k]].nxt=i;
        now[k]=i;
    }
    for(Ll i=1;i<=n;i++){
        cin>>c;
        kk=c;
        k=head[kk];
        head[kk]=a[head[kk]].nxt;
        k=n-k+1;
        ans+=out(k);
        add(k);
    }
    cout<<ans;
}
posted @ 2017-04-07 15:59  largecube233  阅读(129)  评论(0编辑  收藏  举报