P3531 [POI2012]LIT-Letters
题目描述
Little Johnny has a very long surname.
Yet he is not the only such person in his milieu.
As it turns out, one of his friends from kindergarten, Mary, has a surname of the same length, though different from Johnny's.
Moreover, their surnames contain precisely the same number of letters of each kind - the same number of letters A, same of letters B, and so on.
Johnny and Mary took to one another and now often play together.
One of their favourite games is to gather a large number of small pieces of paper, write successive letters of Johnny's surname on them, and then shift them so that they obtain Mary's surname in the end.
Since Johnny loves puzzles, he has begun to wonder how many swaps of adjacent letters are necessary to turn his surname into Mary's. For a child his age, answering such question is a formidable task.
Therefore, soon he has asked you, the most skilled programmer in the kindergarten, to write a program that will help him.
给出两个长度相同且由大写英文字母组成的字符串A、B,保证A和B中每种字母出现的次数相同。
现在每次可以交换A中相邻两个字符,求最少需要交换多少次可以使得A变成B。
输入输出格式
输入格式:In the first line of the standard input there is a single integer () denoting the length of Johnny's surname.
The second line contains Johnny's surname itself, i.e., contains its successive letters (without spaces).
The third line contains Mary's surname in the same format: a string of letters (with no spaces either).
Both strings consist only of capital (upper-case) letters of the English alphabet.
In tests worth 30% of points it additionally holds that .
输出格式:Your program should print a single integer to the standard output: the minimum number of swaps of adjacent letters that transforms Johnny's surname into Mary's.
输入输出样例
3
ABC
BCA
2
说明
给出两个长度相同且由大写英文字母组成的字符串A、B,保证A和B中每种字母出现的次数相同。
现在每次可以交换A中相邻两个字符,求最少需要交换多少次可以使得A变成B。
Solution:
本题将串转为数组,以目标串为样本,将操作串排序离散(记录每个字符在目标串中的位置)。
然后每次交换相邻两数,等价于冒泡排序,即求离散后的数组中逆序对的个数。
那么树状数组求一波就$OK$了。
代码:
#include<bits/stdc++.h> #define il inline #define ll long long #define For(i,a,b) for(int (i)=(a);(i)<=(b);(i)++) #define Bor(i,a,b) for(int (i)=(b);(i)>=(a);(i)--) using namespace std; const int N=1000005; char s[N],t[N]; int n,c[N]; ll node[N],ans; struct node{ int v,id; bool operator<(const node a)const{return v==a.v?id<a.id:v<a.v;} }a[N],b[N]; il void update(int k){while(k<=n){node[k]++;k+=k&-k;}} il ll query(int k){ ll sum=0; while(k){ sum+=node[k]; k-=k&-k; } return sum; } int main(){ scanf("%d",&n); scanf("%s%s",s+1,t+1); For(i,1,n){ a[i].v=s[i]-'A'+1;a[i].id=i; b[i].v=t[i]-'A'+1;b[i].id=i; } sort(a+1,a+n+1);sort(b+1,b+n+1); For(i,1,n)c[a[i].id]=b[i].id; Bor(i,1,n){ update(c[i]); ans+=query(c[i]-1); } cout<<ans; return 0; }