AtCoder problem 017

C++ solution:

Crystal solution: # ac-library.cr by hakatashi https://github.com/google/ac-library.cr
#
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

module AtCoder
  # Implements [atcoder::fenwick_tree](https://atcoder.github.io/ac-library/master/document_en/fenwicktree.html).
  #
  # ```
  # tree = AtCoder::FenwickTree(Int64).new(10)
  # tree.add(3, 10)
  # tree.add(5, 20)
  # tree[3..5]  # => 30
  # tree[3...5] # => 10
  # ```
  class FenwickTree(T)
    getter size : Int64
    getter bits : Array(T)

    def initialize(@size)
      @bits = Array(T).new(@size, T.zero)
    end

    # Implements atcoder::fenwick_tree.add(index, value)
    def add(index, value)
      index += 1 # convert to 1-indexed
      while index <= @size
        @bits[index - 1] += value
        index += index & -index
      end
    end

    # Exclusive left sum
    def left_sum(index)
      ret = T.zero
      while index >= 1
        ret += @bits[index - 1]
        index -= index & -index
      end
      ret
    end

    # Implements atcoder::fenwick_tree.sum(left, right)
    def sum(left, right)
      left_sum(right) - left_sum(left)
    end

    # :ditto:
    def [](range : Range(Int, Int))
      left = range.begin
      right = range.exclusive? ? range.end : range.end + 1
      sum(left, right)
    end
  end
end

n, m = read_line.split.map(&.to_i)
lr = (1..m).map { {Int32, Int32}.from read_line.split.map(&.to_i.pred) }

cnt = [0i64] * n
cnt_r = [0i64] * n
lr.each do |(l, r)|
  cnt[l] += 1
  cnt[r] += 1
  cnt_r[r] += 1
end
sum_r = cnt_r.reduce([0i64]) do |acc, x|
  acc << acc[-1] + x
end

ans = m.to_i64 * m.pred // 2
ans -= cnt.sum { |x| x * x.pred // 2 }
ans -= lr.sum { |(l, r)| sum_r[l] }

sum_l = AtCoder::FenwickTree(Int64).new(n.to_i64)
lr.sort_by { |(l, r)| {r, l} }.each do |(l, r)|
  ans -= sum_l[l + 1...r]
  sum_l.add(l, 1i64)
end

puts ans


Python solution: # でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
def main():
    input = sys.stdin.readline
    N, M = map(int, input().split())
    S = [[] for _ in range(N)]
    T = [[] for _ in range(N)]
    E = []
    for i in range(M):
        s, t = map(lambda x: int(x) - 1, input().split())
        S[s].append(i)
        T[t].append(i)
        E.append((s, t))
    st = SegmentTree(N, f=lambda a, b: a + b)
    ans = 0
    for n in range(N):
        for i in T[n]:
            s, t = E[i]
            st.modify_at(s, -1)
        for i in T[n]:
            s, t = E[i]
            ans += st.query(s + 1, t)
        st.modify_at(n, len(S[n]))
    print(ans)

class SegmentTree:
    __slots__ = ('__n', '__d', '__f', '__e')

    def __init__(self, n=None, f=max, identity_factory=int, initial_values=None):
        assert(n or initial_values)
        size = n if n else len(initial_values)
        d = [identity_factory() for _ in range(2 * size + 1)]
        self.__n, self.__d, self.__f, self.__e = size, d, f, identity_factory
        if initial_values:
            for i, v in enumerate(initial_values): d[size + i] = v
            for i in range(size - 1, 0, -1): d[i] = f(d[i << 1], d[i << 1 | 1])

    def __repr__(self) -> str:
        n = self.__n
        return str([self.get_at(i) for i in range(n)])

    def get_at(self, index):
        return self.__d[index + self.__n]

    def set_at(self, index, new_value):
        i, d, f = index + self.__n, self.__d, self.__f
        if d[i] == new_value: return
        d[i], i = new_value, i >> 1
        while i: d[i], i = f(d[i << 1], d[i << 1 | 1]), i >> 1

    def modify_at(self, index, value):
        self.set_at(index, self.__f(self.__d[index + self.__n], value))

    def query(self, from_inclusive, to_exclusive):
        ans = self.__e()
        if to_exclusive <= from_inclusive: return ans
        l, r, d, f = from_inclusive + self.__n, to_exclusive + self.__n, self.__d, self.__f
        while l < r:
            if l & 1: ans, l = f(ans, d[l]), l + 1
            if r & 1: ans, r = f(d[r - 1], ans), r - 1
            l, r = l >> 1, r >> 1
        return ans

    def query_all(self):
        return self.__d[1]

    def bisect_left(self, func, from_inclusive=None, to_exclusive=None):
        '''func()がTrueになるもっとも左のindexを探す
        '''
        n, f, d, v = self.__n, self.__f, self.__d, self.__e()
        l = (from_inclusive if from_inclusive else 0) + n
        r = (to_exclusive if to_exclusive else n) + n
        h = 0
        while l < r:
            if l & 1:
                nv = f(v, d[l])
                if func(nv): return self.__single_bisect_left(func, l, v)
                v, l = nv, l + 1
            l, r, h = l >> 1, r >> 1, h + 1
        if r == 0: return n
        for i in range(h, 0, -1):
            if ((r + 1) << i <= n + n):
                nv = f(v, d[r])
                if func(nv): return self.__single_bisect_left(func, r, v)
                v, r = nv, r + 1
            r <<= 1
        return n

    def __single_bisect_left(self, func, root, left_val):
        n, f, d = self.__n, self.__f, self.__d
        i, v = root, left_val
        while i < n:
            i <<= 1
            nv = f(v, d[i])
            if not func(nv): i, v = i + 1, nv
        return i - n

if __name__ == '__main__':
    main()