Description
给出两个长度相同且由大写英文字母组成的字符串A、B,保证A和B中每种字母出现的次数相同。
现在每次可以交换A中相邻两个字符,求最少需要交换多少次可以使得A变成B。
Input
第一行一个正整数n (2<=n<=1,000,000),表示字符串的长度。
第二行和第三行各一个长度为n的字符串,并且只包含大写英文字母。
Output
一个非负整数,表示最少的交换次数。
Sample Input
3
ABC
BCA
Sample Output
2
HINT
ABC -> BAC -> BCA
麻瓜题,直接树状数组逆序对。
#include <bits/stdc++.h>
#define lowbit(x) x&(-x)
#define LL long long
#define digit (ch < '0' || ch > '9')
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
const int maxn = 1000005;
LL n,ans;
char a[maxn],b[maxn];
int val[maxn],t[maxn];
queue<int> q[30];
inline void add(int x, int val) { for(int i = x; i <= n; i += lowbit(i)) t[i] += val; }
inline int query(int x, int sum) { for(x; x; x -= lowbit(x)) sum += t[x]; return sum; }
int main() {
scanf("%d%s%s",&n,a+1,b+1);
for(register int i = 1; i <= n; i++) q[a[i]-'A'].push(i);
for(register int i = 1; i <= n; i++) val[i]=q[b[i]-'A'].front(), q[b[i]-'A'].pop();
for(register int i = 1; i <= n; i++) ans += query(n, 0)-query(val[i], 0), add(val[i], 1);
printf(AUTO, ans);
return 0;
}