曜酱的心意
ChikaChika说希望和我一起做学园偶像的时候,我真的很开心。——WatanabeYouWatanabeYou
曜是千歌的青梅竹马,但是AqoursAqours成立以后,千歌似乎总是与梨子在一起,而把曜冷落了。
为了让千歌知晓自己的心意,曜酱决定做一件大事!
她决定把一个给定的11~nn的排列{a1,a2,…,an}{a1,a2,…,an}(1≤ai≤n1≤ai≤n,且aiai各不相同),
用最少的交换次数,变换成另一个11~nn的排列{b1,b2,…,bn}{b1,b2,…,bn}。并且,每次只交换相邻的两个元素。
也许这样做了以后,千歌能更多地注意自己吧。曜这样想。
Input
第一行是一个整数nn,
第二行是一个长度为nn的11~nn的排列aa,
第三行是另一个长度为nn的11~nn的排列bb。
Output
输出一行,一个整数,表示最少的交换次数。
Sample Input
4
2 3 1 4
3 2 1 4
3
3 2 1
1 2 3
Sample Output
1
3
#include<cstdio>
const int maxn = 1e5 + 500;
typedef long long LL;
LL a[maxn],b[maxn],c[maxn];
int n;
LL fun(LL a[maxn])
{
for (int i = 0; i <= n; i++)
c[i] = 0;
LL s = 0;
for (int i = n; i >= 1; i--) {
for (int pos = a[i]; pos > 0; pos -= pos&(-pos))
s += c[pos];
for (int pos = a[i]; pos <= n; pos += pos&(-pos))
c[pos]++;
}
return s;
}
int main()
{
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; i++) {
int x;
scanf("%d",&x);
a[x] = i;
}
for (int i = 1; i <= n; i++) {
int x;
scanf("%d",&x);
b[i] = a[x];
}
LL ans = fun(b);
printf("%lld\n", ans);
}
}