归并做法:
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1000010;
int n,a[N],b[N],w[N],ans;
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*10+ch-'0';ch=getchar();}
return x*f;
}
void merge(int l,int r)
{
if(l==r) return;
int mid=l+r>>1;
int i=l,j=mid+1,k=l;
merge(l,mid);
merge(mid+1,r);
while(i<=mid&&j<=r)
{
if(a[i]<=a[j]) w[k++]=a[i++];
else
{
w[k++]=a[j++];
ans+=mid-i+1;
}
}
while(i<=mid) w[k++]=a[i++];
while(j<=r) w[k++]=a[j++];
for(int i=l;i<=r;i++) a[i]=w[i];
}
signed main()
{
n=read();
for(int i=1;i<=n;i++)
{
b[i]=read();
b[i]-=i;
}
for(int i=1;i<=n;i++) a[i]=b[n-i+1];
merge(1,n);
printf("%lld",ans%12345);
return 0;
}
树状数组:
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define lowbit(x) (x&-x)
const int N=1000010;
int n,m,aa[N],a[N],b[N],tree[N],ans;
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*10+ch-'0';ch=getchar();}
return x*f;
}
void add(int x)
{
for(;x<=n;x+=lowbit(x)) tree[x]++;
}
int query(int x)
{
return lower_bound(a+1,a+m+1,x)-a;
}
int ask(int x)
{
int res=0;
for(;x;x-=lowbit(x)) res+=tree[x];
return res;
}
signed main()
{
n=read();
for(int i=1;i<=n;i++)
{
aa[i]=read();
aa[i]=aa[i]-i+1;
b[i]=aa[i];
}
sort(aa+1,aa+n+1);
for(int i=1;i<=n;i++)
if(i==1||aa[i]!=aa[i-1]) a[++m]=aa[i];
for(int i=1;i<=n;i++)
{
int tmp=query(b[i]);
add(tmp);
ans+=ask(tmp-1);
}
printf("%lld",ans%12345);
return 0;
}