题目链接:https://codeforces.com/problemset/problem/1430/E
分析先将字符串reverse一下,然后从后往前遍历,每次遍历一个字符,找到这个字符在原串中的最后一个位置,将其移动过来即可。
简化一下,相当于每次将某个字符的最右边一个移动到最右边(用过以后要去掉),先记录每个字符的位置
p
o
s
pos
pos,然后记录这个字符前面有
x
x
x个字符已经被移走了,答案就加上
n
−
p
o
s
−
x
n-pos-x
n−pos−x。
每个位置的
x
x
x值可以用树状数组来维护,维护区间修改。
#includeusing namespace std; typedef long long ll; #define fi first #define se second #define pb push_back #define MP make_pair const int inf = 1e9 + 10; const int N = 2e5 + 10; int n; ll c1[N],c2[N]; vector p[26]; char s[N]; int lowbit(int x){return x & -x;} void update(int x, int y)//区间修改:[1, x]的值+y { for (int i = x;i <= n;i += lowbit(i)) c1[i] += y,c2[i] += 1ll * x * y; } ll getsum(int x)//区间查询:[1, x]的值的和 { ll ans1 = 0; ll ans2 = 0; for (int i = x;i > 0;i -= lowbit(i)) { ans1 += (x + 1) * c1[i]; ans2 += c2[i]; } return ans1 - ans2; } int main() { int T = 1; //scanf("%d",&T); while(T--) { for(int i=0;i<26;i++) p[i].clear(); scanf("%d",&n); scanf("%s",s + 1); for(int i=1;i<=n;i++) { p[s[i] - 'a'].pb(i); } reverse(s + 1, s + 1 + n); ll ans = 0; for(int i=n;i>=1;i--) { int ch = s[i] - 'a'; int pos = p[ch][p[ch].size() - 1]; ans += n - pos; p[ch].erase(p[ch].end() - 1); ans -= getsum(pos) - getsum(pos - 1); update(1, 1); update(pos, -1); } printf("%lld",ans); } return 0; } */



