【BZOJ2789】【树状数组】[Poi2012]Letters 题解

本文介绍了一种通过计算逆序对来确定将字符串A转换成字符串B所需的最小交换次数的方法。给定两个长度相等的大写字母字符串A和B,在保证每种字母出现次数相同的情况下,利用树状数组计算最少的交换次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值