首页 > 代码库 > AC日记——Cards Sorting codeforces 830B

AC日记——Cards Sorting codeforces 830B

Cards Sorting

 

思路:

  线段树;

 

代码:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;#define maxn 100005#define INF 0x3f3f3f3f#define maxtree maxn<<2int n,ai[maxn],val[maxtree],L[maxtree],R[maxtree],Min[maxtree];int P[maxtree],mid[maxtree];inline void in(int &now){    char Cget=getchar();now=0;    while(Cget>9||Cget<0) Cget=getchar();    while(Cget>=0&&Cget<=9)    {        now=now*10+Cget-0;        Cget=getchar();    }}void updata(int now){    val[now]=val[now<<1]+val[now<<1|1];    Min[now]=min(Min[now<<1],Min[now<<1|1]);    if(Min[now]==Min[now<<1|1]) P[now]=P[now<<1|1];    else P[now]=P[now<<1];}void build(int now,int l,int r){    L[now]=l,R[now]=r;    if(l==r)    {        Min[now]=ai[l],P[now]=l,val[now]=1;        return;    }    mid[now]=l+r>>1;    build(now<<1,l,mid[now]);    build(now<<1|1,mid[now]+1,r);    updata(now);}void change(int now,int to){    if(L[now]==R[now])    {        val[now]=0,Min[now]=INF,P[now]=0;        return;    }    if(to<=mid[now]) change(now<<1,to);    else change(now<<1|1,to);    updata(now);}int query(int now,int l,int r){    if(L[now]>=l&&R[now]<=r) return val[now];    int res=0;    if(l<=mid[now]) res+=query(now<<1,l,r);    if(r>mid[now]) res+=query(now<<1|1,l,r);    return res;}int get(int now,int l,int r){    if(L[now]>=l&&R[now]<=r) return P[now];    int tmp1=0,tmp2=0;    if(l<=mid[now]) tmp1=get(now<<1,l,r);    if(r>mid[now]) tmp2=get(now<<1|1,l,r);    if(tmp2&&tmp1)    {        if(ai[tmp1]<ai[tmp2]) return tmp1;        else return tmp2;    }    if(tmp2) return tmp2;    if(tmp1) return tmp1;    return 0;}int main(){    in(n);    for(int i=1;i<=n;i++) in(ai[i]);    int l=1,r=n;while(l<r) swap(ai[l],ai[r]),l++,r--;    build(1,1,n);    int now=n,tmp1,tmp2,tmp;    long long ans=0;    for(int i=1;i<=n;i++)    {        tmp1=0,tmp2=0,tmp1=get(1,1,now);        if(now<n) tmp2=get(1,now+1,n);        if(tmp1&&tmp2)        {            if(ai[tmp2]<ai[tmp1]) tmp=tmp2;            else tmp=tmp1;        }        else if(tmp1) tmp=tmp1;        else tmp=tmp2;        if(tmp<=now) ans+=query(1,tmp,now);        else ans+=query(1,1,now)+query(1,tmp,n);        change(1,tmp),now=tmp;    }    cout<<ans;    return 0;}

 

AC日记——Cards Sorting codeforces 830B