using
System;
using
System.Collections.Generic;
class
GFG{
public
class
FenwickTree
{
public
int
[]bit;
int
n;
public
FenwickTree(
int
n)
{
this
.n = n + 1;
bit =
new
int
[n];
}
public
FenwickTree(List<
int
> a)
{
for
(
int
i = 0; i < a.Count; i++)
add(i, a[i]);
}
public
int
sum(
int
idx)
{
int
ret = 0;
idx = idx + 1;
while
(idx > 0)
{
ret += bit[idx];
idx -= idx & (-idx);
}
return
ret;
}
public
void
add(
int
idx,
int
val)
{
idx = idx + 1;
while
(idx <= n)
{
bit[idx] += val;
idx += idx & (-idx);
}
}
public
void
update(
int
idx,
int
val)
{
add(idx, val - valat(idx));
}
public
int
sum(
int
l,
int
r)
{
return
sum(r) - sum(l - 1);
}
public
int
valat(
int
i)
{
return
sum(i, i);
}
public
void
clr(
int
sz)
{
n = sz + 1;
bit =
new
int
[n + 1];
for
(
int
i = 0; i < n; i++)
add(i, 1);
}
};
static
void
charactersCount(String str,
int
n)
{
int
i, count = 0;
List<
int
> []mp =
new
List<
int
>[26];
for
(i = 0; i < mp.Length; i++)
mp[i] =
new
List<
int
>();
FenwickTree ft =
new
FenwickTree(n);
ft.clr(n);
for
(i = 0; i < 26; i++)
mp[i].Clear();
i = 0;
foreach
(
char
ch
in
str.ToCharArray())
{
mp[ch -
'a'
].Add(i);
i++;
}
for
(i = 0; i < 26; i++)
{
foreach
(
int
ind
in
mp[i])
{
count += ft.sum(ind);
ft.update(ind, 0);
}
}
Console.Write(count +
"\n"
);
}
public
static
void
Main(String[] args)
{
String str =
"aabbc"
;
int
n = 5;
charactersCount(str, n);
}
}