先一遍reverse+逆序对个数。
要开long long啊。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxn 100500 using namespace std; int n,a[maxn],pos[maxn],l,bit[maxn]; long long ans=0; int lowbit(int x) {return (x&(-x));} void rev(int l,int r) { for (int i=l;i<=r;i++) { if ((i<<1)>=l+r) break; swap(a[i],a[l+r-i]); } } int ask(int now) { int ret=0; for (int i=now;i>=1;i-=lowbit(i)) ret+=bit[i]; return ret; } void insert(int now,int val) { for (int i=now;i<=n;i+=lowbit(i)) bit[i]+=val; } int main() { scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&a[i]); l=1; for (int i=2;i<=n;i++) { if (a[i]>a[i-1]) { rev(l,i-1); l=i;ans++; } } rev(l,n);ans++; for (int i=1;i<=n;i++) pos[a[i]]=i; for (int i=n;i>=1;i--) { ans+=(long long)ask(pos[i]-1); insert(pos[i],1); } printf("%lld ",ans); return 0; } //Flaze naive!