题目链接:https://www.luogu.com.cn/problem/P5149
解题思路:这道题目需要先开一个数组 (a[i]) 表示一开始应该在第 (i) 个位置上的人现在的位置。然后用归并排序对 (a) 数组求逆序对。
实现代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
string s;
int n, a[maxn], b[maxn];
long long ans;
map<string, int> mp;
void merge_sort(int L, int R) {
if (L == R) return;
int mid = (L + R)/2;
merge_sort(L, mid);
merge_sort(mid+1, R);
int i = L, j = mid+1, k = L;
while (i <= mid && j <= R) {
if (a[i] < a[j]) {
ans += j-(mid+1);
b[k++] = a[i++];
}
else {
b[k++] = a[j++];
}
}
while (i <= mid) {
ans += j-(mid+1);
b[k++] = a[i++];
}
while (j <= R) {
b[k++] = a[j++];
}
for (int i = L; i <= R; i ++) a[i] = b[i];
}
int main() {
cin >> n;
for (int i = 1; i <= n; i ++) {
cin >> s;
mp[s] = i;
}
for (int i = 1; i <= n; i ++) {
cin >> s;
a[ mp[s] ] = i;
}
merge_sort(1, n);
cout << ans << endl;
return 0;
}