BZOJ 1106 立方体大作战

Posted on 2016-09-13 15:38  ziliuziliu  阅读(215)  评论(0编辑  收藏  举报

BIT.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 200050
using namespace std;
int n,t[maxn],x,pos[maxn],ans=0;
int lowbit(int x)
{
    return (x&(-x));
}
int query(int x)
{
    int ret=0;
    for (int i=x;i>=1;i-=lowbit(i))
        ret+=t[i];
    return ret;
}
void add(int x,int val)
{
    for (int i=x;i<=2*n+1;i+=lowbit(i))
        t[i]+=val;
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=2*n;i++)
    {
        scanf("%d",&x);
        if (!pos[x]) pos[x]=i;
        else 
        {
            ans+=(i+query(i))-(pos[x]+query(pos[x]))-1;
            add(pos[x]+1,-1);add(i,1);
            add(i+1,-2);add(2*n+1,2);
        }
    }
    printf("%d\n",ans);
    return 0;
}