逆序对的经典题目。考试的时候不知道怎么写丑了,全WA了,正好带我复习了一遍逆序对。
将火柴序列从小到大分配一个等级,当a的等级与对应的b的等级相同时,答案最小,至于为什么是这样,我就不证明了。这里的等级,实际上就是离散化。
把a的等级从小到大排序之后,再把b对应a的等级排序,求出现在b的等级序列中的逆序对,就是我们要求的交换次数,因为每交换一次,只能使一组逆序对变成有序的。
注意暴搜求逆序对是要超时的,只能得70分,因此用树状数组求和才能过。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 100005
#define mod 99999997
using namespace std;
struct T
{
int num;
int pos;
}a[MAXN],b[MAXN];
int tree[MAXN];
int c[MAXN];
int n;
bool cmp1(T x,T y)
{
return x.num < y.num;
}
int lowbit(int x)
{
return x&-x;
}
void update(int pos)
{
for(int i = pos; i <= n; i += lowbit(i))
tree[i]++;
}
int getsum(int pos)
{
int res = 0;
for(int i = pos; i >= 1; i -= lowbit(i))
res = (res+tree[i])%mod;
return res;
}
int main()
{
scanf("%d",&n);
for(int i = 1; i <= n; i++) {scanf("%d",&a[i].num); a[i].pos = i;}
for(int i = 1; i <= n; i++) {scanf("%d",&b[i].num); b[i].pos = i;}
sort(a+1,a+n+1,cmp1);
sort(b+1,b+n+1,cmp1);
for(int i = 1; i <= n; i++)
c[a[i].pos] = b[i].pos;
int ans = 0;
for(int i = 1; i <= n; i++)
{
update(c[i]);
ans = (ans + i - getsum(c[i]))%mod;
}
printf("%d\n",ans);
return 0;
}