BZOJ2789 [Poi2012]Letters 【树状数组】

题目链接

BZOJ

题解

如果我们给(A)中所有字母按顺序编号,给(B)中所有字母编上相同的号码
对于(B)中同一种,显然号码应该升序
然后求逆序对即可

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
#define lbt(x) (x & -x)
using namespace std;
const int maxn = 1000005,maxm = 100005,INF = 1000000000;
inline int read(){
	int out = 0,flag = 1; char c = getchar();
	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
	return out * flag;
}
vector<int> pos[26];
int now[26],n,a[maxn],s[maxn];
char A[maxn],B[maxn];
void add(int u){while (u <= n) s[u]++,u += lbt(u);}
int query(int u){int re = 0; while (u) re += s[u],u -= lbt(u); return re;}
LL ans;
int main(){
	n = read(); int x;
	scanf("%s",A + 1); scanf("%s",B + 1);
	REP(i,n) pos[A[i] - 'A'].push_back(i);
	REP(i,n) x = B[i] - 'A',a[i] = pos[x][now[x]++];
	for (int i = n; i; i--){
		ans += query(a[i]);
		add(a[i]);
	}
	printf("%lld
",ans);
	return 0;
}

原文地址:https://www.cnblogs.com/Mychael/p/9236945.html