P1966 火柴排队
https://www.luogu.org/problem/show?pid=1966
求逆序对
用树状数组。
#include<iostream> #include<cstdio> #include<algorithm> #include<queue> #include<cstring> #include<cmath> using namespace std;//60fen const int N=100009; const long long P=99999997; struct node{ int x;//数值 int w;//原来位置 }A[N],B[N]; int n; bool cmp(node a,node b) { return a.x<=b.x; } int c[N],d[N]; int Add(int x) { int ans=0; for(int i=x;i<=n;i+=i&(-i)) c[i]=(c[i]+1)%P; for(int i=x;i>0;i-=i&(-i)) ans=(ans+c[i])%P; return ans; } int main() { // freopen("match.in","r",stdin); // freopen("match.out","w",stdout); scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&A[i].x); A[i].w=i; } for(int i=1;i<=n;i++) { scanf("%d",&B[i].x); B[i].w=i; } sort(A+1,A+1+n,cmp); sort(B+1,B+1+n,cmp); for(int i=1;i<=n;i++) d[A[i].w]=B[i].w; long long ans=0; for(int i=1;i<=n;i++) { ans=(ans+i-Add(d[i]))%P; } cout<<ans; return 0; }