BZOJ 4989: [Usaco2017 Feb]Why Did the Cow Cross the Road

来源:互联网 发布:第三方物流模式的优化 编辑:程序博客网 时间:2024/06/06 01:38

做水题一开始还看错题。。。
其实就是求逆序对个数 树状数组搞一下就好了
每次把最后一个调到前面 只用考虑它的影响 其它是不变的
A,B都一样 分别搞一次就好了

#include<bits/stdc++.h>using namespace std;typedef long long LL;const int N=1e5+5;inline int read(){    int x=0,f=1; char ch=getchar();    while(ch<'0' || ch>'9'){if(ch=='-')f=-1; ch=getchar();}    while(ch>='0' && ch<='9'){x=(x<<1)+(x<<3)+ch-'0'; ch=getchar();}    return x*f;}int a[N],b[N],c[N],t[N],n;void add(int x,int u){for(;x<=n;x+=x&-x)t[x]+=u;}int get(int x){int s=0;for(;x;x-=x&-x)s+=t[x];return s;}int main(){    n=read(); int i;    for(i=1;i<=n;++i)a[i]=read(),c[a[i]]=i;    for(i=1;i<=n;++i)b[i]=read();    LL s=0,ans=1e16;    for(i=n;i;--i){        s+=get(c[b[i]]);        add(c[b[i]],1);    }    for(i=n;i;--i){        ans=min(s,ans);        s-=n-get(c[b[i]]);        s+=get(c[b[i]]-1);    }    for(i=1;i<=n;++i)t[i]=0,c[b[i]]=i;    s=0;    for(i=n;i;--i){        s+=get(c[a[i]]);        add(c[a[i]],1);    }    for(i=n;i;--i){        ans=min(s,ans);        s-=n-get(c[a[i]]);        s+=get(c[a[i]]-1);    }    printf("%lld\n",ans);    return 0;}
阅读全文
1 0