public void solve() { int n = sc.Int; var p = new int[n]; var l = new int[n]; var r = new int[n]; var idx = new int[n]; for (int i = 0; i < n; i++) { idx[i] = i; sc.Multi(out p[i], out l[i], out r[i]); } var cmp = compress(p, l, r); p = p.Select(x => cmp[x]).ToArray(); l = l.Select(x => cmp[x]).ToArray(); r = r.Select(x => cmp[x]).ToArray(); Array.Sort(idx, (i, j) => p[i].CompareTo(p[j])); var ql = new PriorityQueue <int>((i, j) => l[j].CompareTo(l[i])); var qr = new PriorityQueue <int>((i, j) => r[j].CompareTo(r[i])); for (int i = 0; i < n; i++) { ql.Push(i); } var bit = new BIT(cmp.Count); long ans = 0; foreach (var i in idx) { while (ql.Count > 0 && l[ql.Top] <= p[i]) { int x = ql.Pop(); bit.add(p[x], 1); qr.Push(x); } while (qr.Count > 0 && r[qr.Top] < p[i]) { int x = qr.Pop(); bit.add(p[x], -1); } ans += bit.sum(l[i], r[i] + 1); } for (int i = 0; i < n; i++) { if (l[i] <= p[i] && p[i] <= r[i]) { --ans; } } Assert(ans % 2 == 0); Prt(ans / 2); } // end Solver.solve
static void Main() { var s = sc.Str; int n = s.Length; var ind = new List <int> [26]; for (int i = 0; i < 26; i++) { ind[i] = new List <int>(); } var bit = new BIT(n); for (int i = 0; i < n; i++) { ind[s[i] - 'a'].Add(i); bit.add(i, 1); } int oc = 0; var l = new int[26]; var r = new int[26]; for (int i = 0; i < 26; i++) { r[i] = ind[i].Count - 1; if (ind[i].Count % 2 == 1) { ++oc; } } if (oc > 1) { DBG(-1); return; } long sum = 0; while (true) { int min = M, minid = -1; for (int i = 0; i < 26; i++) { if (l[i] >= r[i]) { continue; } int cos = (int)(bit.sum(ind[i][l[i]]) + bit.sum(ind[i][r[i]] + 1, n)); if (cos < min) { min = cos; minid = i; } } if (min == M) { break; } sum += min; bit.add(ind[minid][l[minid]], -1); bit.add(ind[minid][r[minid]], -1); ++l[minid]; --r[minid]; } Prt(sum); sw.Flush(); }