P3660 Why Did the Cow Cross the Road 讲解

· · 算法·理论

::::info[AC code]

//#pragma GCC optimize(3)
#include<cstdio>
#include<algorithm>
using namespace std;
inline int read()
{
    int x=0,f=1;
    char s;
    s=getchar();
    while(s<48||s>57)
    {
        if(s=='-')f=-f;
        s=getchar();
    }
    while(s>47&&s<58)
    {
        x=(x<<3)+(x<<1)+(s-48);
        s=getchar();
    }
    return x*f;
}
const int N=5e4+1;
int n;
pair<int,int> a[N<<1];
int sum[N<<1];
long long ans,ans2;
int lowbit(int x)
{
    return x&-x;
}
void update(int x,int v)
{
    for(;x<=n<<1;x+=lowbit(x))sum[x]+=v;
}
int query(int x)
{
    int res=0;
    for(;x;x-=lowbit(x))res+=sum[x];
    return res;
}
int main()
{
    n=read();
    int i,j,x;
    for(i=1;i<=n<<1;++i)
    {
        x=read();
        if(!a[x].first)a[x].first=i;
        else a[x].second=i;
    }
    sort(a+1,a+1+n);
    for(i=1;i<=n;++i)
    {
        ans+=query(a[i].second-1)-query(a[i].first);//查询已插入的区间右端点数量
        update(a[i].second,1);//插入右端点
    }
    printf("%lld",ans);
    return 0;
}

::::