[CC-COUPLES] couples sit next to each other:
You\ (n \ le5 \ times10 ^ 5) \) sat in a circle with friends \ (2N. At the beginning, people numbered \ (I \) sat in the \ (I \) seat. Each time, two adjacent people can exchange seats. How many exchanges are required for each pair of seats adjacent to each other?
Ideas:
The answer is the logarithm of a pair of friends whose distance is the sum of two people-"crossover. Tree array maintenance.
Time Complexity \ (\ mathcal O (N \ log n )\).
Source code:
#include<cstdio>#include<cctype>#include<algorithm>inline int getint() { register char ch; while(!isdigit(ch=getchar())); register int x=ch^'0'; while(isdigit(ch=getchar())) x=(((x<<2)+x)<<1)+(ch^'0'); return x;}typedef long long int64;const int N=5e5+1;int n,a[N*2],pos[N][2],cnt[N];class FenwickTree { private: int val[N*2]; int lowbit(const int &x) const { return x&-x; } public: void modify(int p,const int &x) { for(;p<=n*2;p+=lowbit(p)) { val[p]+=x; } } int query(int p) const { int ret=0; for(;p;p-=lowbit(p)) { ret+=val[p]; } return ret; } int query(const int &l,const int &r) const { return query(r)-query(l-1); }};FenwickTree t;int main() { for(register int T=getint();T;T--) { n=getint(); std::fill(&cnt[1],&cnt[n]+1,0); for(register int i=1;i<=n*2;i++) { const int &x=a[i]=getint(); pos[x][cnt[x]++]=i; } int64 ans=0; for(register int i=1;i<=n;i++) { ans+=std::min(pos[i][1]-pos[i][0],n*2+pos[i][0]-pos[i][1])-1; } for(register int i=1;i<=n*2;i++) { const int &x=a[i]; if(i==pos[x][0]) { t.modify(i,1); } if(i==pos[x][1]) { t.modify(pos[x][0],-1); ans-=t.query(pos[x][0],i); } } printf("%lld\n",ans); } return 0;}
[CC-COUPLES] couples sit next to each other