Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- typedef long double ld;
- typedef long long int ll;
- typedef pair<int, int> pi;
- typedef pair<long long, long long> pll;
- #define endl '\n'
- #define ff first
- #define ss second
- #define pb push_back
- #define int long long
- #define sz(v) (int)v.size()
- #define inf 2147483647
- #define llinf 9223372036854775807
- #define all(v) v.begin(),v.end()
- #define bp(n) __builtin_popcountll(n)
- #define f(i,l,r) for(long long i=l;i<=r;i++)
- #define rf(i,r,l) for(long long i=r;i>=l;i--)
- #define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
- template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
- template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
- template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
- void dbg_out() { cerr << endl; }
- template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
- const int N = 1e5 + 5, mod = 1e9 + 7, bit = 61;
- template<typename T>
- class fenwick
- {
- public:
- vector<T> fen;
- int n;
- fenwick() {}
- fenwick(int _n, T val = T())
- {
- n = _n;
- fen = vector<T> (n + 1, val);
- }
- T merge(T a, T b)
- {
- return a + b;
- }
- void update(int idx, T val)
- {
- while (idx <= n)
- {
- fen[idx] = merge(fen[idx], val);
- idx += (idx & -idx);
- }
- }
- T query(int idx)
- {
- T ans{};
- while (idx > 0)
- {
- ans = merge(ans, fen[idx]);
- idx -= (idx & -idx);
- }
- return ans;
- }
- T from(int l, int r)
- {
- return query(r) - query(l - 1);
- }
- };
- vector<int> adj[26];
- signed main()
- {
- fast;
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- int t = 1;
- //cin >> t;
- f(tc, 1, t)
- {
- int n;
- cin >> n;
- string fw, bw;
- cin >> fw;
- reverse(all(fw));
- bw = fw;
- reverse(all(fw));
- fw = '#' + fw;
- bw = '#' + bw;
- fenwick<int> obj(n);
- f(i, 1, n)
- {
- int id = fw[i] - 'a';
- adj[id].pb(i);
- }
- int ans = 0;
- rf(i, n, 1)
- {
- int id = bw[i] - 'a';
- int x = adj[id].back();
- adj[id].pop_back();
- int nx = x + obj.query(x);
- obj.update(x, -1);
- ans += i - nx;
- }
- cout << ans << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement