結果

問題 No.1115 二つの数列 / Two Sequences
ユーザー kyo1
提出日時 2020-09-27 01:00:59
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 83 ms / 2,000 ms
コード長 1,364 bytes
コンパイル時間 751 ms
コンパイル使用メモリ 82,544 KB
最終ジャッジ日時 2025-01-14 22:41:14
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstddef>
#include <iostream>
#include <map>
#include <vector>

template <typename T = int>
class FenwickTree {
 private:
  std::vector<T> tree;

 public:
  explicit FenwickTree(const std::size_t n) : tree(n + 1, 0) {}

  explicit FenwickTree(const std::vector<T>& vec) : tree(vec.size() + 1) {
    for (std::size_t i = 0; i < vec.size(); i++) {
      add(i, vec[i]);
    }
  }

  std::size_t size() const { return tree.size() - 1; }

  void add(const std::size_t idx, const T x) {
    for (std::size_t i = idx + 1; i < tree.size(); i += i & (~i + 1)) {
      tree[i] += x;
    }
  }

  T query(const std::size_t idx) const {
    T res = 0;
    for (std::size_t i = idx; i != 0; i &= i - 1) {
      res += tree[i];
    }
    return res;
  }

  T query(const std::size_t l, const std::size_t r) const { return query(r) - query(l); }
};

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int N;
  std::cin >> N;
  std::vector<int> A(N), B(N);
  for (auto&& e : A) {
    std::cin >> e;
  }
  std::map<int, int> table;
  for (int i = 0; i < N; i++) {
    table[A[i]] = i;
  }
  for (int i = 0; i < N; i++) {
    int b;
    std::cin >> b;
    B[i] = table[b];
  }
  FenwickTree ft(N);
  int64_t res = 0;
  for (int i = 0; i < N; i++) {
    res += i - ft.query(B[i]);
    ft.add(B[i], 1);
  }
  std::cout << res << '\n';
  return 0;
}
0