library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub maspypy/library

:heavy_check_mark: test/3_yukicoder/1600_2.test.cpp

Depends on

Code

#define PROBLEM "https://yukicoder.me/problems/no/1600"
#include "my_template.hpp"
#include "other/io.hpp"

#include "ds/wavelet_matrix/wavelet_matrix_2d_range.hpp"
#include "ds/static_range_product.hpp"

#include "alg/monoid/min.hpp"
#include "graph/tree.hpp"
#include "ds/unionfind/unionfind.hpp"

#include "mod/modint.hpp"
using mint = modint107;

void solve() {
  LL(N, M);
  Graph<mint, 0> G(N);
  UnionFind uf(N);
  vc<pair<int, int>> edges;
  vc<bool> in_G(M);
  mint wt = 1;
  FOR(i, M) {
    LL(a, b);
    --a, --b;
    edges.eb(a, b);
    wt += wt;
    if (uf.merge(a, b)) {
      in_G[i] = 1;
      G.add(a, b, wt);
    }
  }
  G.build();

  Tree<decltype(G)> tree(G);
  auto& par = tree.parent;
  vc<int> X, Y, W;
  FOR(e, M) {
    if (in_G[e]) continue;
    auto [a, b] = edges[e];
    a = tree.LID[a], b = tree.LID[b];
    if (a > b) swap(a, b);
    X.eb(a), Y.eb(b), W.eb(e);
  }

  using Mono = Monoid_Min<int>;
  using ST = Sparse_Table<Mono>;
  Wavelet_Matrix_2D_Range<int, false, false, Static_Range_Product<Mono, ST>>
      seg(len(X),
          [&](int i) -> tuple<int, int, int> { return {X[i], Y[i], W[i]}; });

  LL(Q);
  FOR(Q) {
    LL(u, v, idx);
    --u, --v, --idx;
    auto [x, y] = edges[idx];
    if (par[y] == x) swap(x, y);
    bool in_u = tree.in_subtree(u, x);
    bool in_v = tree.in_subtree(v, x);
    if (!in_G[idx] || in_u == in_v) {
      print(tree.dist_weighted(u, v));
      continue;
    }
    // 木の外に出る移動が必要
    int l = tree.LID[x], r = tree.RID[x];
    int min_i = Mono::op(seg.prod(0, l, l, r), seg.prod(l, r, r, N));
    if (min_i == Mono::id()) {
      print(-1);
      continue;
    }
    auto [p, q] = edges[min_i];
    bool in_p = tree.in_subtree(p, x);
    if (!in_u) swap(u, v);
    if (!in_p) swap(p, q);
    mint ANS = tree.dist_weighted(u, p) + tree.dist_weighted(v, q);
    ANS += mint(2).pow(min_i + 1);
    print(ANS);
  }
}

signed main() {
  solve();
  return 0;
}
#line 1 "test/3_yukicoder/1600_2.test.cpp"
#define PROBLEM "https://yukicoder.me/problems/no/1600"
#line 1 "my_template.hpp"
#if defined(USE_PCH)
#include <my_template_compiled.hpp>
#else
#if defined(__GNUC__)
#include <bits/allocator.h>
#pragma GCC optimize("Ofast,unroll-loops")
// 環境によってはコンパイル成功かつ実行時エラー
#pragma GCC target("avx2,popcnt")
#endif
#include <bits/stdc++.h>
#include <cassert>

using namespace std;

using ll = long long;
using u8 = uint8_t;
using u16 = uint16_t;
using u32 = uint32_t;
using u64 = uint64_t;
using i128 = __int128;
using u128 = unsigned __int128;
using f128 = __float128;

template <class>
constexpr bool dependent_false = false;

template <class T>
constexpr T infty = [] {
  static_assert(dependent_false<T>, "infty<T> is not defined");
  return T{};
}();
template <>
constexpr int infty<int> = 1'010'000'000;
template <>
constexpr ll infty<ll> = 2'020'000'000'000'000'000;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * 2'000'000'000'000'000'000;
template <>
constexpr double infty<double> = infty<i128>;
template <>
constexpr long double infty<long double> = infty<i128>;

using pi = pair<ll, ll>;
using vi = vector<ll>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using pq_max = priority_queue<T>;
template <class T>
using pq_min = priority_queue<T, vector<T>, greater<T>>;

#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR1_R(a) for (ll i = ll(a) - 1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = ll(a) - 1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = ll(b) - 1; i >= ll(a); --i)
#define overload3(a, b, c, d, ...) d
#define FOR(...) overload3(__VA_ARGS__, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) overload3(__VA_ARGS__, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define all(x) (x).begin(), (x).end()
#define len(x) ll(x.size())
#define elif else if

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll

// require y > 0
template <typename T>
T floor(T x, T y) {
  return x / y - (x % y < 0);
}

// require y > 0
template <typename T>
T ceil(T x, T y) {
  return (x / y) + (x % y > 0);
}

// require y > 0
template <typename T>
T bmod(T x, T y) {
  T r = x % y;
  return (r < 0 ? r + y : r);
}

// require y > 0
template <typename T>
pair<T, T> divmod(T x, T y) {
  T q = x / y, r = x % y;
  if (r < 0) --q, r += y;
  return {q, r};
}

constexpr auto TEN = [] {
  array<u64, 20> A{};
  A[0] = 1;
  for (int i = 1; i < 20; ++i) A[i] = 10 * A[i - 1];
  return A;
}();

template <typename T, typename U>
T SUM(const U &A) {
  return std::accumulate(A.begin(), A.end(), T{});
}

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
template <class C, class T>
inline long long LB(const C &c, const T &x) {
  return lower_bound(c.begin(), c.end(), x) - c.begin();
}
template <class C, class T>
inline long long UB(const C &c, const T &x) {
  return upper_bound(c.begin(), c.end(), x) - c.begin();
}
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())

template <typename T>
T POP(deque<T> &que) {
  T a = que.front();
  que.pop_front();
  return a;
}
template <class T, class Container, class Compare>
T POP(priority_queue<T, Container, Compare> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(vc<T> &que) {
  T a = que.back();
  que.pop_back();
  return a;
}

template <typename F>
i128 binary_search(F check, i128 ok, i128 ng, bool check_ok = true) {
  if (check_ok) assert(check(ok));
  while (1) {
    i128 x = (ok + ng) / 2;
    if (x == ok || x == ng) break;
    (check(x) ? ok : ng) = x;
  }
  return ok;
}

template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
  FOR(iter) {
    double x = (ok + ng) / 2;
    (check(x) ? ok : ng) = x;
  }
  return (ok + ng) / 2;
}

template <class T, class S>
inline bool chmax(T &a, const S &b) {
  T c = max<T>(a, b);
  bool changed = (c != a);
  a = c;
  return changed;
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
  T c = min<T>(a, b);
  bool changed = (c != a);
  a = c;
  return changed;
}

// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
  vc<int> A(S.size());
  FOR(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
  return A;
}

template <typename T, typename U>
vc<T> cumsum(const vc<U> &A, int off = 1) {
  int N = A.size();
  vc<T> B(N + 1);
  FOR(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

// stable sort
template <typename T>
vc<int> argsort(const vc<T> &A) {
  vc<int> ids(len(A));
  iota(all(ids), 0);
  sort(all(ids),
      [&](int i, int j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
  vc<T> B(len(I));
  FOR(i, len(I)) B[i] = A[I[i]];
  return B;
}

template <typename T, typename... Vectors>
void concat(vc<T> &first, const Vectors &...others) {
  first.reserve(first.size() + (others.size() + ... + 0));
  (first.insert(first.end(), others.begin(), others.end()), ...);
}

// i128
template <class T, enable_if_t<is_same_v<T, i128>, int> = 0>
constexpr i128 abs(T x) {
  return x < 0 ? -x : x;
}

constexpr i128 gcd(i128 a, i128 b) {
  while (b != 0) {
    i128 c = a % b;
    a = b, b = c;
  }
  return abs(a);
}
#endif
#line 1 "other/io.hpp"
#define FASTIO

// https://judge.yosupo.jp/submission/21623

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf

uint32_t pil = 0, pir = 0, por = 0;
bool input_eof = false;

template <class T>
constexpr bool is_signed_integer_v = is_signed_v<T> || is_same_v<T, i128>;

template <class T>
struct unsigned_integer {
  using type = make_unsigned_t<T>;
};
template <>
struct unsigned_integer<i128> {
  using type = u128;
};
template <>
struct unsigned_integer<u128> {
  using type = u128;
};
template <class T>
using unsigned_integer_t = typename unsigned_integer<T>::type;

[[noreturn]] inline void input_error(const char *message) {
  fputs(message, stderr);
  fputc('\n', stderr);
  exit(EXIT_FAILURE);
}

struct Pre {
  char num[10000][4];
  constexpr Pre() : num() {
    for (int i = 0; i < 10000; i++) {
      int n = i;
      for (int j = 3; j >= 0; j--) {
        num[i][j] = n % 10 | '0';
        n /= 10;
      }
    }
  }
} constexpr pre;

inline void load() {
  uint32_t n = pir - pil;
  memmove(ibuf, ibuf + pil, n);
  pil = 0;
  pir = n;
  if (input_eof) return;

  pir += fread(ibuf + pir, 1, SZ - pir, stdin);
  if (ferror(stdin)) input_error("fastio: input error");
  if (feof(stdin)) {
    input_eof = true;
    // Allows the last token to end exactly at EOF without a trailing

    // whitespace.

    if (pir < SZ) ibuf[pir++] = '\n';
  }
}

inline char get_char() {
  if (pil == pir) {
    load();
    if (pil == pir) input_error("fastio: unexpected EOF");
  }
  return ibuf[pil++];
}

inline void flush() {
  fwrite(obuf, 1, por, stdout);
  por = 0;
}

void rd(char &c) {
  do c = get_char();
  while (isspace(static_cast<unsigned char>(c)));
}

void rd(string &x) {
  x.clear();
  char c;
  do c = get_char();
  while (isspace(static_cast<unsigned char>(c)));
  do {
    x += c;
    c = get_char();
  } while (!isspace(static_cast<unsigned char>(c)));
}

template <typename T>
void rd_real(T &x) {
  string s;
  rd(s);
  x = stod(s);
}

template <typename T>
void rd_integer_slow(T &x) {
  char c;
  do c = get_char();
  while (c < '-');
  bool minus = 0;
  if constexpr (is_signed_integer_v<T>) {
    if (c == '-') {
      minus = 1, c = get_char();
    }
  }
  x = 0;
  assert('0' <= c && c <= '9');
  while ('0' <= c && c <= '9') {
    x = x * 10 + (c & 15), c = get_char();
  }
  assert(isspace(static_cast<unsigned char>(c)));
  if constexpr (is_signed_integer_v<T>) {
    if (minus) x = -x;
  }
}

template <typename T>
void rd_integer(T &x) {
  if (pil + 100 > pir) {
    load();
    if (pil + 100 > pir) {
      rd_integer_slow(x);
      return;
    }
  }
  char c;
  do c = ibuf[pil++];
  while (c < '-');
  bool minus = 0;
  if constexpr (is_signed_integer_v<T>) {
    if (c == '-') {
      minus = 1, c = ibuf[pil++];
    }
  }
  x = 0;
  assert('0' <= c && c <= '9');
  while ('0' <= c && c <= '9') {
    x = x * 10 + (c & 15), c = ibuf[pil++];
  }
  assert(isspace(static_cast<unsigned char>(c)));
  if constexpr (is_signed_integer_v<T>) {
    if (minus) x = -x;
  }
}

template <class T>
enable_if_t<is_integral_v<T> || is_same_v<T, i128> || is_same_v<T, u128>> rd(
    T &x) {
  rd_integer(x);
}

template <class T>
enable_if_t<is_floating_point_v<T> || is_same_v<T, f128>> rd(T &x) {
  rd_real(x);
}

template <class T, class U>
void rd(pair<T, U> &p) {
  rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T>
void rd_tuple(T &t) {
  if constexpr (N < tuple_size<T>::value) {
    auto &x = get<N>(t);
    rd(x);
    rd_tuple<N + 1>(t);
  }
}
template <class... T>
void rd(tuple<T...> &tpl) {
  rd_tuple(tpl);
}

template <class T, size_t N>
void rd(array<T, N> &x) {
  for (auto &d : x) rd(d);
}
template <class T>
void rd(vc<T> &x) {
  for (auto &d : x) rd(d);
}

template <class... T>
void read(T &...x) {
  (rd(x), ...);
}

inline void wt_range(const char *s, size_t n) {
  size_t i = 0;
  while (i < n) {
    if (por == SZ) flush();
    size_t chunk = min(n - i, (size_t)(SZ - por));
    memcpy(obuf + por, s + i, chunk);
    por += chunk;
    i += chunk;
  }
}

void wt(const char c) {
  if (por == SZ) flush();
  obuf[por++] = c;
}
void wt(const char *s) { wt_range(s, strlen(s)); }
void wt(const string &s) { wt_range(s.data(), s.size()); }

template <typename T>
void wt_integer(T x) {
  if (por > SZ - 100) flush();
  using U = unsigned_integer_t<T>;
  U y = static_cast<U>(x);
  if constexpr (is_signed_integer_v<T>) {
    if (x < 0) {
      obuf[por++] = '-';
      y = U(0) - y;
    }
  }
  int outi;
  for (outi = 96; y >= 10000; outi -= 4) {
    memcpy(out + outi, pre.num[y % 10000], 4);
    y /= 10000;
  }
  if (y >= 1000) {
    memcpy(obuf + por, pre.num[y], 4);
    por += 4;
  } else if (y >= 100) {
    memcpy(obuf + por, pre.num[y] + 1, 3);
    por += 3;
  } else if (y >= 10) {
    int q = (y * 103) >> 10;
    obuf[por] = q | '0';
    obuf[por + 1] = (y - q * 10) | '0';
    por += 2;
  } else
    obuf[por++] = y | '0';
  memcpy(obuf + por, out + outi + 4, 96 - outi);
  por += 96 - outi;
}

template <typename T>
inline void wt_real(T x) {
  static char buf[1000];
  int n = std::snprintf(buf, sizeof(buf), "%.15f", (double)x);
  wt_range(buf, (size_t)n);
}

template <class T>
enable_if_t<is_integral_v<T> || is_same_v<T, i128> || is_same_v<T, u128>> wt(
    T x) {
  wt_integer(x);
}

template <class T>
enable_if_t<is_floating_point_v<T> || is_same_v<T, f128>> wt(T x) {
  wt_real(x);
}

inline void wt(bool b) { wt(static_cast<char>('0' + (b ? 1 : 0))); }

template <class T, class U>
void wt(const pair<T, U> &val) {
  wt(val.first);
  wt(' ');
  wt(val.second);
}
template <size_t N = 0, typename T>
void wt_tuple(const T &t) {
  if constexpr (N < tuple_size<T>::value) {
    if constexpr (N > 0) wt(' ');
    wt(get<N>(t));
    wt_tuple<N + 1>(t);
  }
}
template <class... T>
void wt(const tuple<T...> &tpl) {
  wt_tuple(tpl);
}
template <class T, size_t S>
void wt(const array<T, S> &val) {
  auto n = val.size();
  for (size_t i = 0; i < n; i++) {
    if (i) wt(' ');
    wt(val[i]);
  }
}
template <class T>
void wt(const vector<T> &val) {
  auto n = val.size();
  for (size_t i = 0; i < n; i++) {
    if (i) wt(' ');
    wt(val[i]);
  }
}

void print() { wt('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&...tail) {
  wt(forward<Head>(head));
  ((wt(' '), wt(forward<Tail>(tail))), ...);
  wt('\n');
}

// gcc expansion. called automaticall after main.

void __attribute__((destructor)) _d() { flush(); }
}  // namespace fastio

using fastio::flush;
using fastio::print;
using fastio::read;

#if defined(LOCAL)
#define HDR "[DEBUG:", __func__, __LINE__, "]"
#define SHOW(...)                                                         \
  SHOW_IMPL(__VA_ARGS__, SHOW8, SHOW7, SHOW6, SHOW5, SHOW4, SHOW3, SHOW2, \
            SHOW1)                                                        \
  (__VA_ARGS__)
#define SHOW_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, NAME, ...) NAME
#define SHOW1(x) print(HDR, #x, "=", (x)), flush()
#define SHOW2(x, y) print(HDR, #x, "=", (x), #y, "=", (y)), flush()
#define SHOW3(x, y, z) \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z)), flush()
#define SHOW4(x, y, z, w) \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w)), flush()
#define SHOW5(x, y, z, w, v)                                                  \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v)),                                                                 \
      flush()
#define SHOW6(x, y, z, w, v, u)                                               \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v), #u, "=", (u)),                                                   \
      flush()
#define SHOW7(x, y, z, w, v, u, t)                                            \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v), #u, "=", (u), #t, "=", (t)),                                     \
      flush()
#define SHOW8(x, y, z, w, v, u, t, s)                                         \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v), #u, "=", (u), #t, "=", (t), #s, "=", (s)),                       \
      flush()
#else
#define SHOW(...)
#endif

#define INT(...)   \
  int __VA_ARGS__; \
  read(__VA_ARGS__)
#define LL(...)   \
  ll __VA_ARGS__; \
  read(__VA_ARGS__)
#define U32(...)   \
  u32 __VA_ARGS__; \
  read(__VA_ARGS__)
#define U64(...)   \
  u64 __VA_ARGS__; \
  read(__VA_ARGS__)
#define STR(...)      \
  string __VA_ARGS__; \
  read(__VA_ARGS__)
#define CHAR(...)   \
  char __VA_ARGS__; \
  read(__VA_ARGS__)
#define DBL(...)      \
  double __VA_ARGS__; \
  read(__VA_ARGS__)

#define VEC(type, name, size) \
  vector<type> name(size);    \
  read(name)
#define VV(type, name, h, w)                     \
  vector<vector<type>> name(h, vector<type>(w)); \
  read(name)

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
void YA(bool t = 1) { print(t ? "YA" : "TIDAK"); }
void TIDAK(bool t = 1) { YA(!t); }
void Alice(bool t = 1) { print(t ? "Alice" : "Bob"); }
void Bob(bool t = 1) { Alice(!t); }
#line 4 "test/3_yukicoder/1600_2.test.cpp"

#line 1 "other/bit.hpp"

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
int popcnt_sgn(int x) { return (__builtin_parity(unsigned(x)) & 1 ? -1 : 1); }
int popcnt_sgn(u32 x) { return (__builtin_parity(x) & 1 ? -1 : 1); }
int popcnt_sgn(ll x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
int popcnt_sgn(u64 x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T kth_bit(int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return T(1) << k;
}
template <typename T>
bool has_kth_bit(T x, int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return x >> k & 1;
}

template <typename UINT>
struct all_bit {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_bit(UINT s) : s(s) {}
  struct iter {
    UINT s;
    int operator*() const { return lowbit(s); }
    void operator++() { s &= s - 1; }
    bool operator!=(nullptr_t) const { return s; }
  };
  iter begin() const { return {s}; }
  nullptr_t end() const { return nullptr; }
};

template <typename UINT>
struct all_subset {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_subset(UINT s) : s(s) {}
  struct iter {
    UINT s, t;
    bool done = false;
    UINT operator*() const { return t; }
    void operator++() {
      done = (t == 0);
      t = (t - 1) & s;
    }
    bool operator!=(nullptr_t) const { return !done; }
  };
  iter begin() const { return {s, s}; }
  nullptr_t end() const { return nullptr; }
};

constexpr u64 full_mask(int n) {
  assert(0 <= n && n <= 64);
  return n == 64 ? -1ULL : (1ULL << n) - 1;
}

u64 bit_reverse(u64 x) {
  x = ((x & 0x5555555555555555ULL) << 1) | ((x >> 1) & 0x5555555555555555ULL);
  x = ((x & 0x3333333333333333ULL) << 2) | ((x >> 2) & 0x3333333333333333ULL);
  x = ((x & 0x0f0f0f0f0f0f0f0fULL) << 4) | ((x >> 4) & 0x0f0f0f0f0f0f0f0fULL);
  x = ((x & 0x00ff00ff00ff00ffULL) << 8) | ((x >> 8) & 0x00ff00ff00ff00ffULL);
  x = ((x & 0x0000ffff0000ffffULL) << 16) | ((x >> 16) & 0x0000ffff0000ffffULL);
  x = (x << 32) | (x >> 32);
  return x;
}
#line 2 "ds/bit_vector.hpp"

struct Bit_Vector {
  int n;
  bool prepared = 0;
  vc<pair<u64, u32>> dat;
  Bit_Vector(int n = 0) : n(n) { dat.assign((n + 127) >> 6, {0, 0}); }
  void set(int i) {
    assert(!prepared && (0 <= i && i < n));
    dat[i >> 6].fi |= u64(1) << (i & 63);
  }
  void reset() {
    fill(all(dat), pair<u64, u32>{0, 0});
    prepared = 0;
  }
  void build() {
    prepared = 1;
    FOR(i, len(dat) - 1) dat[i + 1].se = dat[i].se + popcnt(dat[i].fi);
  }
  bool operator[](int i) const { return dat[i >> 6].fi >> (i & 63) & 1; }
  // [0, k) 内の 1 の個数
  int count_prefix(int k, bool f = true) const {
    assert(prepared);
    auto [a, b] = dat[k >> 6];
    int ret = b + popcnt(a & ((u64(1) << (k & 63)) - 1));
    return (f ? ret : k - ret);
  }
  int count(int L, int R, bool f = true) const {
    return count_prefix(R, f) - count_prefix(L, f);
  }
  string to_string() const {
    string ans;
    FOR(i, n) ans += '0' + (dat[i / 64].fi >> (i % 64) & 1);
    return ans;
  }
};
#line 1 "alg/monoid/dummy.hpp"
struct Monoid_Dummy {
  using value_type = char;
  static constexpr bool commute = true;
  static value_type op(value_type, value_type) { return 0; }
  static value_type id() { return 0; }
};
#line 2 "ds/dummy_data_structure.hpp"

struct Dummy_Data_Structure {
  using MX = Monoid_Dummy;
  using T = typename MX::value_type;
  void build(const vc<T>& A) {}
};
#line 3 "ds/wavelet_matrix/wavelet_matrix.hpp"

template <typename Y, typename SEGTREE>
struct Uncompressed_Wavelet_Matrix {
  using Mono = typename SEGTREE::MX;
  using T = typename Mono::value_type;
  static_assert(Mono::commute);
  static_assert(is_same_v<Y, int> || is_same_v<Y, ll>);
  int n = 0, log = 0;
  vc<int> mid;
  vc<Bit_Vector> bv;
  vc<SEGTREE> seg;
  Y limit;

  Uncompressed_Wavelet_Matrix() = default;

  // f(i) = {A[i], dat[i]}

  template <typename F>
  Uncompressed_Wavelet_Matrix(int n, F f, int log = -1) {
    build(n, f, log);
  }
  Uncompressed_Wavelet_Matrix(const vc<Y>& A, int log = -1) {
    static_assert(is_same_v<SEGTREE, Dummy_Data_Structure>);
    build(len(A), [&](int i) -> pair<Y, T> { return {A[i], Mono::id()}; }, log);
  }

  template <typename F>
  void build(int n, F f, int log = -1) {
    this->n = n;
    vc<Y> A(n);
    vc<T> S(n);
    FOR(i, n) tie(A[i], S[i]) = f(i);
    if (log == -1) {
      log = (n == 0 ? 0 : topbit(MAX(A)) + 1);
    } else {
      for (auto& x : A) assert(0 <= x && topbit(x) < log);
    }
    this->log = log;
    limit = Y(1) << log;
    if constexpr (is_same_v<Y, int>) assert(0 <= log && log <= 30);
    if constexpr (is_same_v<Y, ll>) assert(0 <= log && log <= 62);
    mid.resize(log), bv.assign(log, Bit_Vector(n));
    vc<Y> A0(n), A1(n);
    vc<T> S0(n), S1(n);
    seg.resize(log + 1);
    seg[log].build(S);
    for (int d = log - 1; d >= 0; --d) {
      int p0 = 0, p1 = 0;
      for (int i = 0; i < n; ++i) {
        if (A[i] >> d & 1) {
          bv[d].set(i), A1[p1] = A[i], S1[p1] = S[i], p1++;
        } else {
          A0[p0] = A[i], S0[p0] = S[i], p0++;
        }
      }
      swap(A, A0), swap(S, S0);
      move(A1.begin(), A1.begin() + p1, A.begin() + p0);
      move(S1.begin(), S1.begin() + p1, S.begin() + p0);
      mid[d] = p0, bv[d].build(), seg[d].build(S);
    }
  }

  tuple<int, int, int, int> get_subtree(int d, int L, int R) const {
    assert(1 <= d && d <= log);
    int a = bv[d - 1].count_prefix(L), b = bv[d - 1].count_prefix(R);
    return {L - a, R - b, mid[d - 1] + a, mid[d - 1] + b};
  }

  template <typename F>
  void work_point(F f, int i) {
    assert(0 <= i && i < n);
    f(log, i);
    FOR_R(d, log) {
      int a = bv[d].count_prefix(i);
      if (bv[d][i]) {
        i = mid[d] + a;
      } else {
        i = i - a;
      }
      f(d, i);
    }
  }

  template <typename F>
  void work_prefix(F f, int L, int R, Y y) const {
    chmin(y, limit);
    if (y == 0) return;
    if (y == limit) {
      f(log, L, R);
      return;
    }
    FOR_R(d, log) {
      auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
      if (y >> d & 1) {
        f(d, L0, R0);
        L = L1, R = R1;
      } else {
        L = L0, R = R0;
      }
    }
  }

  template <typename F>
  void work_range(F f, int L, int R, Y y1, Y y2) const {
    chmin(y2, limit);
    if (y1 >= y2) return;
    assert(0 <= y1 && y1 <= y2 && y2 <= limit);
    if (y1 == 0) return work_prefix(f, L, R, y2);
    auto dfs = [&](auto& dfs, int d, int L, int R, Y y1, Y y2) -> void {
      if (y1 == y2) return;
      if (y1 == 0 && y2 == Y(1) << d) {
        f(d, L, R);
        return;
      }
      assert(d > 0);
      auto [L0, R0, L1, R1] = get_subtree(d, L, R);
      Y m = (Y(1) << (d - 1));

      if (y2 <= m) {
        dfs(dfs, d - 1, L0, R0, y1, y2);
      } else if (y1 >= m) {
        dfs(dfs, d - 1, L1, R1, y1 - m, y2 - m);
      } else {
        dfs(dfs, d - 1, L0, R0, y1, m);
        dfs(dfs, d - 1, L1, R1, 0, y2 - m);
      }
    };
    dfs(dfs, log, L, R, y1, y2);
  }

  // [L,R) x [0,y)

  int prefix_count(int L, int R, Y y) const {
    int cnt = 0;
    work_prefix([&](int d, int a, int b) { cnt += b - a; }, L, R, y);
    return cnt;
  }

  // [L,R) x [y1,y2)

  int count(int L, int R, Y y1, Y y2) const {
    return prefix_count(L, R, y2) - prefix_count(L, R, y1);
  }

  // [L,R) x [0,y)

  T prefix_prod(int L, int R, Y y) const {
    T ans = Mono::id();
    work_prefix(
        [&](int d, int a, int b) { ans = Mono::op(ans, seg[d].prod(a, b)); }, L,
        R, y);
    return ans;
  }
  // [L,R) x [y1,y2)

  T prod(int L, int R, Y y1, Y y2) const {
    T ans = Mono::id();
    work_range(
        [&](int d, int a, int b) { ans = Mono::op(ans, seg[d].prod(a, b)); }, L,
        R, y1, y2);
    return ans;
  }
  T prod_all(int L, int R) const { return seg[log].prod(L, R); }

  // [L,R) x [0,y)

  pair<int, T> prefix_count_and_prod(int L, int R, Y y) const {
    pair<int, T> ans = {0, Mono::id()};
    work_prefix(
        [&](int d, int a, int b) {
          ans.fi += b - a;
          ans.se = Mono::op(ans.se, seg[d].prod(a, b));
        },
        L, R, y);
    return ans;
  }
  // [L,R) x [y1,y2)

  pair<int, T> count_and_prod(int L, int R, Y y1, Y y2) const {
    pair<int, T> ans = {0, Mono::id()};
    work_range(
        [&](int d, int a, int b) {
          ans.fi += b - a;
          ans.se = Mono::op(ans.se, seg[d].prod(a, b));
        },
        L, R, y1, y2);
    return ans;
  }

  Y kth(int L, int R, int k) const {
    assert(0 <= k && k < R - L);
    Y ans = 0;
    for (int d = log - 1; d >= 0; --d) {
      auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
      if (k < R0 - L0) {
        L = L0, R = R0;
      } else {
        ans |= Y(1) << d;
        k -= R0 - L0, L = L1, R = R1;
      }
    }
    return ans;
  }

  template <bool upper>
  Y median(int L, int R) const {
    assert(0 <= L && L < R && R <= n);
    int k = (upper ? (R - L) / 2 : (R - L - 1) / 2);
    return kth(L, R, k);
  }

  void set(int i, T t) {
    assert(0 <= i && i < n);
    work_point([&](int d, int i) { seg[d].set(i, t); }, i);
  }
  void multiply(int i, T t) {
    assert(0 <= i && i < n);
    work_point([&](int d, int i) { seg[d].multiply(i, t); }, i);
  }
  void add(int i, T t) {
    assert(0 <= i && i < n);
    work_point([&](int d, int i) { seg[d].add(i, t); }, i);
  }

  // [L,R) x [0,y) での check(y, cnt, prod) が true となる最大の (Y,cnt,prod)

  // cnt はデータ件数全体であって, activate/deactivate を考慮する場合には

  // prod の方を見る必要がある

  template <typename F>
  tuple<Y, int, T> max_right(F check, int L, int R) const {
    int cnt = 0;
    Y y = 0;
    T t = Mono::id();
    T t_all = seg[log].prod(L, R);
    assert(check(0, 0, Mono::id()));
    if (check(infty<Y>, R - L, t_all)) {
      return {infty<Y>, R - L, t_all};
    }
    for (int d = log - 1; d >= 0; --d) {
      auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
      Y y1 = y | Y(1) << d;
      int cnt1 = cnt + R0 - L0;
      T t1 = Mono::op(t, seg[d].prod(L0, R0));
      if (check(y1, cnt1, t1)) {
        y = y1, cnt = cnt1, t = t1, L = L1, R = R1;
      } else {
        L = L0, R = R0;
      }
    }
    return {y, cnt, t};
  }

  // [L,R) x [0,y) での check(y, cnt, prod) が true となる最大の (Y,cnt,prod)

  template <typename F>
  tuple<Y, int, T> max_right_many(F check, vc<pair<int, int>> LR) const {
    int cnt = 0;
    Y y = 0;
    T t = Mono::id();
    T t_all = Mono::id();
    int cnt_all = 0;
    for (auto& [l, r] : LR)
      t_all = Mono::op(t_all, prod_all(l, r)), cnt_all += r - l;
    assert(check(0, 0, Mono::id()));
    if (check(infty<Y>, cnt_all, t_all)) {
      return {infty<Y>, cnt_all, t_all};
    }
    for (int d = log - 1; d >= 0; --d) {
      Y y1 = Y(1) << d;
      T t1 = t;
      int cnt1 = 0;
      for (auto& [L, R] : LR) {
        auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
        cnt1 += R0 - L0;
        t1 = Mono::op(t1, seg[d].prod(L0, R0));
      }
      if (check(y1, cnt1, t1)) {
        y = y1, cnt = cnt1, t = t1;
        for (auto& [L, R] : LR) {
          auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
          L = L1, R = R1;
        }
      } else {
        for (auto& [L, R] : LR) {
          auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
          L = L0, R = R0;
        }
      }
    }
    return {y, cnt, t};
  }

  // [L,R) x [y, inf) での check(y, cnt, prod) が true となる最小の (y,cnt,prod)

  // cnt==0 だと true であることは仮定する

  // https://qoj.ac/contest/1047/problem/5094

  template <typename F>
  tuple<Y, int, T> min_left_many(F check, vc<pair<int, int>> LR) const {
    assert(check(limit, 0, Mono::id()));
    int cnt = 0;
    Y y = limit;
    T t = Mono::id();
    T t_all = Mono::id();
    int cnt_all = 0;
    for (auto& [l, r] : LR)
      t_all = Mono::op(t_all, prod_all(l, r)), cnt_all += r - l;
    if (check(0, cnt_all, t_all)) {
      return {0, cnt_all, t_all};
    }
    for (int d = log - 1; d >= 0; --d) {
      Y y1 = y - (Y(1) << d);
      T t1 = t;
      int cnt1 = cnt;
      for (auto& [L, R] : LR) {
        auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
        cnt1 += R1 - L1;
        t1 = Mono::op(t1, seg[d].prod(L1, R1));
      }
      if (check(y1, cnt1, t1)) {
        y = y1, cnt = cnt1, t = t1;
        SHOW(y);
        for (auto& [L, R] : LR) {
          auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
          L = L0, R = R0;
        }
      } else {
        for (auto& [L, R] : LR) {
          auto [L0, R0, L1, R1] = get_subtree(d + 1, L, R);
          L = L1, R = R1;
        }
      }
    }
    SHOW(y, cnt, t);
    return {y, cnt, t};
  }
};

template <typename Y, typename SEGTREE>
struct Compressed_Wavelet_Matrix {
  using Mono = typename SEGTREE::MX;
  using T = typename Mono::value_type;

  int n = 0;
  vc<Y> key;
  Uncompressed_Wavelet_Matrix<int, SEGTREE> wm;

  Compressed_Wavelet_Matrix() = default;

  // f(i) = {A[i], dat[i]}

  template <typename F>
  Compressed_Wavelet_Matrix(int n, F f) {
    build(n, f);
  }

  Compressed_Wavelet_Matrix(const vc<Y>& A) {
    static_assert(is_same_v<SEGTREE, Dummy_Data_Structure>);
    build(A);
  }

  template <typename F>
  void build(int n, F f) {
    this->n = n;
    vc<Y> A(n);
    vc<T> S(n);
    FOR(i, n) tie(A[i], S[i]) = f(i);

    key = A;
    UNIQUE(key);

    wm.build(n, [&](int i) -> pair<int, T> {
      int k = LB(key, A[i]);
      return {k, S[i]};
    });
  }

  void build(const vc<Y>& A) {
    static_assert(is_same_v<SEGTREE, Dummy_Data_Structure>);
    n = len(A);
    key = A;
    UNIQUE(key);

    wm.build(n, [&](int i) -> pair<int, T> {
      int k = LB(key, A[i]);
      return {k, Mono::id()};
    });
  }

  Y kth(int L, int R, int k) const { return key[wm.kth(L, R, k)]; }

  template <bool upper>
  Y median(int L, int R) const {
    return key[wm.template median<upper>(L, R)];
  }

  // [L,R) x [-inf,y)

  int prefix_count(int L, int R, Y y) const {
    return wm.prefix_count(L, R, LB(key, y));
  }

  // [L,R) x [y1,y2)

  int count(int L, int R, Y y1, Y y2) const {
    return wm.count(L, R, LB(key, y1), LB(key, y2));
  }

  // [L,R) x [-inf,y)

  T prefix_prod(int L, int R, Y y) const {
    return wm.prefix_prod(L, R, LB(key, y));
  }

  // [L,R) x [y1,y2)

  T prod(int L, int R, Y y1, Y y2) const {
    return wm.prod(L, R, LB(key, y1), LB(key, y2));
  }

  T prod_all(int L, int R) const { return wm.prod_all(L, R); }

  // [L,R) x [-inf,y)

  pair<int, T> prefix_count_and_prod(int L, int R, Y y) const {
    return wm.prefix_count_and_prod(L, R, LB(key, y));
  }

  // [L,R) x [y1,y2)

  pair<int, T> count_and_prod(int L, int R, Y y1, Y y2) const {
    return wm.count_and_prod(L, R, LB(key, y1), LB(key, y2));
  }

  void set(int i, T t) { wm.set(i, t); }

  void multiply(int i, T t) { wm.multiply(i, t); }

  void add(int i, T t) { wm.add(i, t); }
};

template <typename Y, bool compress, typename SEGTREE = Dummy_Data_Structure>
using Wavelet_Matrix =
    conditional_t<compress, Compressed_Wavelet_Matrix<Y, SEGTREE>,
        Uncompressed_Wavelet_Matrix<Y, SEGTREE>>;
#line 1 "ds/index_compression.hpp"
template <typename T>
struct Index_Compression_DISTINCT_SMALL {
  int mi, ma;
  vc<T> dat;
  vc<T> build(vc<int> X) {
    mi = 0, ma = -1;
    if (!X.empty()) mi = MIN(X), ma = MAX(X);
    dat.assign(ma - mi + 2, 0);
    for (auto& x : X) dat[x - mi + 1]++;
    FOR(i, len(dat) - 1) dat[i + 1] += dat[i];
    for (auto& x : X) {
      x = dat[x - mi]++;
    }
    FOR_R(i, 1, len(dat)) dat[i] = dat[i - 1];
    dat[0] = 0;
    return X;
  }
  int size() const { return len(dat); }
  int val_to_idx(T x) const { return dat[clamp<ll>(x - mi, 0, ma - mi + 1)]; }
  int idx_to_val(int i) const { return dat[i]; }
};

template <typename T>
struct Index_Compression_SAME_SMALL {
  int mi, ma;
  vc<T> dat;
  vc<T> build(vc<T> X) {
    mi = 0, ma = -1;
    if (!X.empty()) mi = MIN(X), ma = MAX(X);
    dat.assign(ma - mi + 2, 0);
    for (auto& x : X) dat[x - mi + 1] = 1;
    FOR(i, len(dat) - 1) dat[i + 1] += dat[i];
    for (auto& x : X) {
      x = dat[x - mi];
    }
    return X;
  }
  int size() const { return len(dat); }
  int val_to_idx(T x) const { return dat[clamp<ll>(x - mi, 0, ma - mi + 1)]; }
  int idx_to_val(int i) const { return dat[i]; }
};

template <typename T>
struct Index_Compression_SAME_LARGE {
  vc<T> dat;
  vc<int> build(const vc<T>& X) {
    dat.reserve(len(X));
    vc<pair<T, int>> tmp(len(X));
    FOR(i, len(X)) tmp[i] = {X[i], i};
    sort(all(tmp));
    vc<int> ANS(len(X));
    for (auto [x, j] : tmp) {
      if (dat.empty() || dat.back() != x) dat.eb(x);
      ANS[j] = len(dat) - 1;
    }
    return ANS;
  }
  int size() const { return len(dat); }
  int val_to_idx(T x) const { return LB(dat, x); }
  int idx_to_val(int i) const { return dat[i]; }
};

template <typename T>
struct Index_Compression_DISTINCT_LARGE {
  vc<T> dat;
  vc<int> build(vc<T> X) {
    dat.reserve(len(X));
    vc<pair<T, int>> tmp(len(X));
    FOR(i, len(X)) tmp[i] = {X[i], i};
    sort(all(tmp));
    vc<int> ANS(len(X));
    for (auto [x, j] : tmp) {
      dat.eb(x);
      ANS[j] = len(dat) - 1;
    }
    return ANS;
  }
  int size() const { return len(dat); }
  int val_to_idx(T x) const { return LB(dat, x); }
  int idx_to_val(int i) const { return dat[i]; }
};

template <typename T, bool SMALL>
using Index_Compression_DISTINCT =
    typename std::conditional<SMALL, Index_Compression_DISTINCT_SMALL<T>,
                              Index_Compression_DISTINCT_LARGE<T>>::type;
template <typename T, bool SMALL>
using Index_Compression_SAME =
    typename std::conditional<SMALL, Index_Compression_SAME_SMALL<T>,
                              Index_Compression_SAME_LARGE<T>>::type;

// SAME: [2,3,2] -> [0,1,0]
// DISTINCT: [2,2,3] -> [0,2,1]
// build で列を圧縮してくれる. そのあと
// (x): lower_bound(X,x) をかえす
template <typename T, bool SAME, bool SMALL>
using Index_Compression =
    typename std::conditional<SAME, Index_Compression_SAME<T, SMALL>,
                              Index_Compression_DISTINCT<T, SMALL>>::type;
#line 3 "ds/wavelet_matrix/wavelet_matrix_2d_range.hpp"

template <typename XY, bool compress_X, bool compress_Y,
          typename SEGTREE = Dummy_Data_Structure>
struct Wavelet_Matrix_2D_Range {
  // 点群を X 昇順に並べる.
  Wavelet_Matrix<XY, compress_Y, SEGTREE> WM;
  using Mono = typename SEGTREE::MX;
  using T = typename Mono::value_type;
  static_assert(Mono::commute);

  Index_Compression<XY, false, !compress_X> IDX_X;

  int n;
  vc<int> new_idx;

  template <typename F>
  Wavelet_Matrix_2D_Range(int n, F f) {
    build(n, f);
  }

  template <typename F>
  void build(int m, F f) {
    n = m;
    vc<XY> X(n), Y(n);
    vc<T> S(n);
    FOR(i, n) {
      auto tmp = f(i);
      X[i] = get<0>(tmp), Y[i] = get<1>(tmp), S[i] = get<2>(tmp);
    }
    new_idx = IDX_X.build(X);
    vc<int> I(n);
    FOR(i, n) I[new_idx[i]] = i;
    Y = rearrange(Y, I);
    S = rearrange(S, I);
    WM.build(n, [&](int i) -> pair<XY, T> { return {Y[i], S[i]}; });
  }

  int count(XY x1, XY x2, XY y1, XY y2) {
    return WM.count(IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2), y1, y2);
  }

  // [L,R) x [-inf,y)
  pair<int, T> prefix_count_and_prod(XY x1, XY x2, XY y) {
    return WM.prefix_count_and_prod(IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2),
                                    y);
  }

  // [L,R) x [y1,y2)
  pair<int, T> count_and_prod(XY x1, XY x2, XY y1, XY y2) {
    return WM.count_and_prod(IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2), y1,
                             y2);
  }

  // [L,R) x [-inf,inf)
  T prod_all(XY x1, XY x2) {
    return WM.prod_all(IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2));
  }
  // [L,R) x [-inf,y)
  T prefix_prod(XY x1, XY x2, XY y) {
    return WM.prefix_prod(IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2), y);
  }
  // [L,R) x [y1,y2)
  T prod(XY x1, XY x2, XY y1, XY y2) {
    return WM.prod(IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2), y1, y2);
  }
  // i は最初に渡したインデックス
  void set(int i, T t) { WM.set(new_idx[i], t); }
  // i は最初に渡したインデックス
  void multiply(int i, T t) { WM.multiply(new_idx[i], t); }
  void add(int i, T t) { WM.multiply(new_idx[i], t); }

  // [L,R) x [0,y) での check(y, cnt, prod) が true となる最大の (Y,cnt,prod)
  // cnt はデータ件数全体であって, activate/deactivate を考慮する場合には
  // prod の方を見る必要がある
  template <typename F>
  tuple<XY, int, T> max_right(F check, XY x1, XY x2) const {
    return WM.max_right(check, IDX_X.val_to_idx(x1), IDX_X.val_to_idx(x2));
  }
};
#line 1 "other/bit.hpp"

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
int popcnt_sgn(int x) { return (__builtin_parity(unsigned(x)) & 1 ? -1 : 1); }
int popcnt_sgn(u32 x) { return (__builtin_parity(x) & 1 ? -1 : 1); }
int popcnt_sgn(ll x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
int popcnt_sgn(u64 x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T kth_bit(int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return T(1) << k;
}
template <typename T>
bool has_kth_bit(T x, int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return x >> k & 1;
}

template <typename UINT>
struct all_bit {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_bit(UINT s) : s(s) {}
  struct iter {
    UINT s;
    int operator*() const { return lowbit(s); }
    void operator++() { s &= s - 1; }
    bool operator!=(nullptr_t) const { return s; }
  };
  iter begin() const { return {s}; }
  nullptr_t end() const { return nullptr; }
};

template <typename UINT>
struct all_subset {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_subset(UINT s) : s(s) {}
  struct iter {
    UINT s, t;
    bool done = false;
    UINT operator*() const { return t; }
    void operator++() {
      done = (t == 0);
      t = (t - 1) & s;
    }
    bool operator!=(nullptr_t) const { return !done; }
  };
  iter begin() const { return {s, s}; }
  nullptr_t end() const { return nullptr; }
};

constexpr u64 full_mask(int n) {
  assert(0 <= n && n <= 64);
  return n == 64 ? -1ULL : (1ULL << n) - 1;
}

u64 bit_reverse(u64 x) {
  x = ((x & 0x5555555555555555ULL) << 1) | ((x >> 1) & 0x5555555555555555ULL);
  x = ((x & 0x3333333333333333ULL) << 2) | ((x >> 2) & 0x3333333333333333ULL);
  x = ((x & 0x0f0f0f0f0f0f0f0fULL) << 4) | ((x >> 4) & 0x0f0f0f0f0f0f0f0fULL);
  x = ((x & 0x00ff00ff00ff00ffULL) << 8) | ((x >> 8) & 0x00ff00ff00ff00ffULL);
  x = ((x & 0x0000ffff0000ffffULL) << 16) | ((x >> 16) & 0x0000ffff0000ffffULL);
  x = (x << 32) | (x >> 32);
  return x;
}
#line 2 "ds/sparse_table/sparse_table.hpp"

// 冪等なモノイドであることを仮定。disjoint sparse table より x 倍高速
template <class Monoid>
struct Sparse_Table {
  using MX = Monoid;
  using X = typename MX::value_type;
  int n, log;
  vvc<X> dat;

  Sparse_Table() {}
  Sparse_Table(int n) { build(n); }
  template <typename F>
  Sparse_Table(int n, F f) {
    build(n, f);
  }
  Sparse_Table(const vc<X>& v) { build(v); }

  void build(int m) {
    build(m, [](int i) -> X { return MX::id(); });
  }
  void build(const vc<X>& v) {
    build(len(v), [&](int i) -> X { return v[i]; });
  }
  template <typename F>
  void build(int m, F f) {
    n = m, log = 1;
    while ((1 << log) < n) ++log;
    dat.resize(log);
    dat[0].resize(n);
    FOR(i, n) dat[0][i] = f(i);

    FOR(i, log - 1) {
      dat[i + 1].resize(len(dat[i]) - (1 << i));
      FOR(j, len(dat[i]) - (1 << i)) {
        dat[i + 1][j] = MX::op(dat[i][j], dat[i][j + (1 << i)]);
      }
    }
  }

  X prod(int L, int R) const {
    if (L == R) return MX::id();
    if (R == L + 1) return dat[0][L];
    int k = topbit(R - L - 1);
    return MX::op(dat[k][L], dat[k][R - (1 << k)]);
  }

  template <class F>
  int max_right(const F check, int L) const {
    assert(0 <= L && L <= n && check(MX::id()));
    if (L == n) return n;
    int ok = L, ng = n + 1;
    while (ok + 1 < ng) {
      int k = (ok + ng) / 2;
      bool bl = check(prod(L, k));
      if (bl) ok = k;
      if (!bl) ng = k;
    }
    return ok;
  }

  template <class F>
  int min_left(const F check, int R) const {
    assert(0 <= R && R <= n && check(MX::id()));
    if (R == 0) return 0;
    int ok = R, ng = -1;
    while (ng + 1 < ok) {
      int k = (ok + ng) / 2;
      bool bl = check(prod(k, R));
      if (bl) ok = k;
      if (!bl) ng = k;
    }
    return ok;
  }
};
#line 1 "other/bit.hpp"

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
int popcnt_sgn(int x) { return (__builtin_parity(unsigned(x)) & 1 ? -1 : 1); }
int popcnt_sgn(u32 x) { return (__builtin_parity(x) & 1 ? -1 : 1); }
int popcnt_sgn(ll x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
int popcnt_sgn(u64 x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T kth_bit(int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return T(1) << k;
}
template <typename T>
bool has_kth_bit(T x, int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return x >> k & 1;
}

template <typename UINT>
struct all_bit {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_bit(UINT s) : s(s) {}
  struct iter {
    UINT s;
    int operator*() const { return lowbit(s); }
    void operator++() { s &= s - 1; }
    bool operator!=(nullptr_t) const { return s; }
  };
  iter begin() const { return {s}; }
  nullptr_t end() const { return nullptr; }
};

template <typename UINT>
struct all_subset {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_subset(UINT s) : s(s) {}
  struct iter {
    UINT s, t;
    bool done = false;
    UINT operator*() const { return t; }
    void operator++() {
      done = (t == 0);
      t = (t - 1) & s;
    }
    bool operator!=(nullptr_t) const { return !done; }
  };
  iter begin() const { return {s, s}; }
  nullptr_t end() const { return nullptr; }
};

constexpr u64 full_mask(int n) {
  assert(0 <= n && n <= 64);
  return n == 64 ? -1ULL : (1ULL << n) - 1;
}

u64 bit_reverse(u64 x) {
  x = ((x & 0x5555555555555555ULL) << 1) | ((x >> 1) & 0x5555555555555555ULL);
  x = ((x & 0x3333333333333333ULL) << 2) | ((x >> 2) & 0x3333333333333333ULL);
  x = ((x & 0x0f0f0f0f0f0f0f0fULL) << 4) | ((x >> 4) & 0x0f0f0f0f0f0f0f0fULL);
  x = ((x & 0x00ff00ff00ff00ffULL) << 8) | ((x >> 8) & 0x00ff00ff00ff00ffULL);
  x = ((x & 0x0000ffff0000ffffULL) << 16) | ((x >> 16) & 0x0000ffff0000ffffULL);
  x = (x << 32) | (x >> 32);
  return x;
}
#line 2 "ds/sparse_table/disjoint_sparse_table.hpp"

template <class Monoid>
struct Disjoint_Sparse_Table {
  using MX = Monoid;
  using X = typename MX::value_type;
  int n, log;
  vvc<X> dat;

  Disjoint_Sparse_Table() {}
  Disjoint_Sparse_Table(int n) { build(n); }
  template <typename F>
  Disjoint_Sparse_Table(int n, F f) {
    build(n, f);
  }
  Disjoint_Sparse_Table(const vc<X>& v) { build(v); }

  void build(int m) {
    build(m, [](int i) -> X { return MX::id(); });
  }
  void build(const vc<X>& v) {
    build(len(v), [&](int i) -> X { return v[i]; });
  }
  template <typename F>
  void build(int m, F f) {
    n = m, log = 1;
    while ((1 << log) < n) ++log;
    dat.resize(log);
    dat[0].reserve(n);
    FOR(i, n) dat[0].eb(f(i));
    FOR(i, 1, log) {
      auto& v = dat[i];
      v = dat[0];
      int b = 1 << i;
      for (int m = b; m <= n; m += 2 * b) {
        int L = m - b, R = min(n, m + b);
        FOR_R(j, L + 1, m) v[j - 1] = MX::op(v[j - 1], v[j]);
        FOR(j, m, R - 1) v[j + 1] = MX::op(v[j], v[j + 1]);
      }
    }
  }

  X prod(int L, int R) const {
    if (L == R) return MX::id();
    --R;
    if (L == R) return dat[0][L];
    int k = topbit(L ^ R);
    return MX::op(dat[k][L], dat[k][R]);
  }

  template <class F>
  int max_right(const F check, int L) const {
    assert(0 <= L && L <= n && check(MX::id()));
    if (L == n) return n;
    int ok = L, ng = n + 1;
    while (ok + 1 < ng) {
      int k = (ok + ng) / 2;
      bool bl = check(prod(L, k));
      if (bl) ok = k;
      if (!bl) ng = k;
    }
    return ok;
  }

  template <class F>
  int min_left(const F check, int R) const {
    assert(0 <= R && R <= n && check(MX::id()));
    if (R == 0) return 0;
    int ok = R, ng = -1;
    while (ng + 1 < ok) {
      int k = (ok + ng) / 2;
      bool bl = check(prod(k, R));
      if (bl) ok = k;
      if (!bl) ng = k;
    }
    return ok;
  }
};
#line 3 "ds/static_range_product.hpp"

/*
参考:https://judge.yosupo.jp/submission/106668
長さ 2^LOG のブロックに分ける.ブロック内の prefix, suffix を持つ.
ブロック積の列を ST(DST) で持つ.ブロックをまたぐ積は O(1).
短いものは O(1) を諦めて愚直ということにする.
前計算:O(Nlog(N)/2^LOG)
クエリ:O(1) / worst O(2^LOG)
*/
template <typename Monoid, typename SPARSE_TABLE, int LOG = 4>
struct Static_Range_Product {
  using MX = Monoid;
  using X = typename MX::value_type;
  int N, b_num;
  vc<X> A, pre, suf;  // inclusive
  SPARSE_TABLE ST;

  Static_Range_Product() {}
  template <typename F>
  Static_Range_Product(int n, F f) {
    build(n, f);
  }
  Static_Range_Product(const vc<X>& v) { build(v); }

  void build(const vc<X>& v) {
    build(len(v), [&](int i) -> X { return v[i]; });
  }
  template <typename F>
  void build(int m, F f) {
    N = m;
    b_num = N >> LOG;
    A.resize(N);
    FOR(i, N) A[i] = f(i);
    pre = A, suf = A;
    constexpr int mask = (1 << LOG) - 1;
    FOR(i, 1, N) {
      if (i & mask) pre[i] = MX::op(pre[i - 1], A[i]);
    }
    FOR_R(i, 1, N) {
      if (i & mask) suf[i - 1] = MX::op(A[i - 1], suf[i]);
    }
    ST.build(b_num, [&](int i) -> X { return suf[i << LOG]; });
  }

  // O(1) or O(R-L)
  X prod(int L, int R) const {
    if (L == R) return MX::id();
    R -= 1;
    int a = L >> LOG, b = R >> LOG;
    if (a < b) {
      X x = ST.prod(a + 1, b);
      x = MX::op(suf[L], x);
      x = MX::op(x, pre[R]);
      return x;
    }
    X x = A[L];
    FOR(i, L + 1, R + 1) x = MX::op(x, A[i]);
    return x;
  }

  template <class F>
  int max_right(const F check, int L) const {
    assert(0 <= L && L <= N && check(MX::id()));
    if (L == N) return N;
    int ok = L, ng = N + 1;
    while (ok + 1 < ng) {
      int k = (ok + ng) / 2;
      bool bl = check(prod(L, k));
      if (bl) ok = k;
      if (!bl) ng = k;
    }
    return ok;
  }

  template <class F>
  int min_left(const F check, int R) const {
    assert(0 <= R && R <= N && check(MX::id()));
    if (R == 0) return 0;
    int ok = R, ng = -1;
    while (ng + 1 < ok) {
      int k = (ok + ng) / 2;
      bool bl = check(prod(k, R));
      if (bl) ok = k;
      if (!bl) ng = k;
    }
    return ok;
  }
};
#line 7 "test/3_yukicoder/1600_2.test.cpp"

#line 1 "alg/monoid/min.hpp"
// require: all values x satisfy x <= infty<E>
template <typename E>
struct Monoid_Min {
  using X = E;
  using value_type = X;
  static constexpr X op(const X &x, const X &y) noexcept { return min(x, y); }
  static constexpr X id() { return infty<E>; }
  static constexpr bool commute = true;
};
#line 1 "graph/tree.hpp"

#line 1 "ds/hashmap.hpp"

// u64 -> Val
template <typename Val>
struct HashMap {
  // n は入れたいものの個数で ok
  HashMap(u32 n = 0) { build(n); }
  void build(u32 n) {
    u32 k = 8;
    while (k < n * 2) k *= 2;
    cap = k / 2, mask = k - 1;
    key.resize(k), val.resize(k), used.assign(k, 0);
  }

  // size を保ったまま. size=0 にするときは build すること.
  void clear() {
    used.assign(len(used), 0);
    cap = (mask + 1) / 2;
  }
  int size() { return len(used) / 2 - cap; }

  int index(const u64& k) {
    int i = 0;
    for (i = hash(k); used[i] && key[i] != k; i = (i + 1) & mask) {
    }
    return i;
  }

  Val& operator[](const u64& k) {
    int i = index(k);
    if (used[i]) return val[i];
    if (cap == 0) extend(), i = index(k);
    used[i] = 1, key[i] = k, val[i] = Val{}, --cap;
    return val[i];
  }

  Val get(const u64& k, Val default_value) {
    int i = index(k);
    return (used[i] ? val[i] : default_value);
  }

  bool count(const u64& k) {
    int i = index(k);
    return used[i] && key[i] == k;
  }

  // f(key, val)
  template <typename F>
  void enumerate_all(F f) {
    FOR(i, len(used)) if (used[i]) f(key[i], val[i]);
  }

 private:
  u32 cap, mask;
  vc<u64> key;
  vc<Val> val;
  vc<bool> used;

  u64 hash(u64 x) {
    static const u64 FIXED_RANDOM =
        std::chrono::steady_clock::now().time_since_epoch().count();
    x += FIXED_RANDOM;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
    return (x ^ (x >> 31)) & mask;
  }

  void extend() {
    vc<pair<u64, Val>> dat;
    dat.reserve(len(used) / 2 - cap);
    FOR(i, len(used)) {
      if (used[i]) dat.eb(key[i], val[i]);
    }
    build(2 * len(dat));
    for (auto& [a, b] : dat) (*this)[a] = b;
  }
};
#line 2 "graph/base.hpp"

template <typename T>
struct Edge {
  int frm, to;
  T cost;
  int id;
};

template <typename T = int, bool directed = false>
struct Graph {
  static constexpr bool is_directed = directed;
  int N, M;
  using cost_type = T;
  using edge_type = Edge<T>;
  vector<edge_type> edges;
  vector<int> indptr;
  vector<edge_type> csr_edges;
  mutable vc<int> vc_deg, vc_indeg, vc_outdeg;
  mutable HashMap<int> MP_FOR_EID;
  bool prepared;

  class OutgoingEdges {
   public:
    OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}

    const edge_type* begin() const {
      if (l == r) {
        return 0;
      }
      return &G->csr_edges[l];
    }

    const edge_type* end() const {
      if (l == r) {
        return 0;
      }
      return &G->csr_edges[r];
    }

   private:
    const Graph* G;
    int l, r;
  };

  bool is_prepared() const { return prepared; }

  Graph() : N(0), M(0), prepared(0) {}
  Graph(int N) : N(N), M(0), prepared(0) {}

  void build(int n) {
    N = n, M = 0;
    prepared = 0;
    edges.clear();
    indptr.clear();
    csr_edges.clear();
    vc_deg.clear();
    vc_indeg.clear();
    vc_outdeg.clear();
    MP_FOR_EID.clear();
  }

  void add(int frm, int to, T cost = 1, int i = -1) {
    assert(!prepared);
    assert(0 <= frm && frm < N && 0 <= to && to < N);
    if (i == -1) i = M;
    auto e = edge_type({frm, to, cost, i});
    edges.eb(e);
    ++M;
  }

#ifdef FASTIO
  // wt, off
  void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }

  void read_graph(int M, bool wt = false, int off = 1) {
    for (int m = 0; m < M; ++m) {
      INT(a, b);
      a -= off, b -= off;
      if (!wt) {
        add(a, b);
      } else {
        T c;
        read(c);
        add(a, b, c);
      }
    }
    build();
  }
#endif

  void build() {
    assert(!prepared);
    prepared = true;
    indptr.assign(N + 1, 0);
    for (auto&& e : edges) {
      indptr[e.frm + 1]++;
      if (!directed) indptr[e.to + 1]++;
    }
    for (int v = 0; v < N; ++v) {
      indptr[v + 1] += indptr[v];
    }
    auto counter = indptr;
    csr_edges.resize(indptr.back() + 1);
    for (auto&& e : edges) {
      csr_edges[counter[e.frm]++] = e;
      if (!directed)
        csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});
    }
  }

  OutgoingEdges operator[](int v) const {
    assert(prepared);
    return {this, indptr[v], indptr[v + 1]};
  }

  vc<int> deg_array() const {
    if (vc_deg.empty()) calc_deg();
    return vc_deg;
  }

  pair<vc<int>, vc<int>> deg_array_inout() const {
    if (vc_indeg.empty()) calc_deg_inout();
    return {vc_indeg, vc_outdeg};
  }

  int deg(int v) const {
    if (vc_deg.empty()) calc_deg();
    return vc_deg[v];
  }

  int in_deg(int v) const {
    if (vc_indeg.empty()) calc_deg_inout();
    return vc_indeg[v];
  }

  int out_deg(int v) const {
    if (vc_outdeg.empty()) calc_deg_inout();
    return vc_outdeg[v];
  }

#ifdef FASTIO
  void debug() {
#ifdef LOCAL
    print("Graph");
    if (!prepared) {
      print("frm to cost id");
      for (auto&& e : edges) print(e.frm, e.to, e.cost, e.id);
    } else {
      print("indptr", indptr);
      print("frm to cost id");
      FOR(v, N) for (auto&& e : (*this)[v]) print(e.frm, e.to, e.cost, e.id);
    }
    flush();
#endif
  }
#endif

  vc<int> new_idx;
  vc<bool> used_e;

  // G における頂点 V[i] が、新しいグラフで i になるようにする
  // {G, es}
  // sum(deg(v)) の計算量になっていて、
  // 新しいグラフの n+m より大きい可能性があるので注意
  Graph<T, directed> rearrange(vc<int> V, bool keep_eid = 0) {
    if (len(new_idx) != N) new_idx.assign(N, -1);
    int n = len(V);
    FOR(i, n) new_idx[V[i]] = i;
    Graph<T, directed> G(n);
    vc<int> history;
    FOR(i, n) {
      for (auto&& e : (*this)[V[i]]) {
        if (len(used_e) <= e.id) used_e.resize(e.id + 1);
        if (used_e[e.id]) continue;
        int a = e.frm, b = e.to;
        if (new_idx[a] != -1 && new_idx[b] != -1) {
          history.eb(e.id);
          used_e[e.id] = 1;
          int eid = (keep_eid ? e.id : -1);
          G.add(new_idx[a], new_idx[b], e.cost, eid);
        }
      }
    }
    FOR(i, n) new_idx[V[i]] = -1;
    for (auto&& eid : history) used_e[eid] = 0;
    G.build();
    return G;
  }

  Graph<T, true> to_directed_tree(int root = -1) const {
    if (root == -1) root = 0;
    assert(!is_directed && prepared && M == N - 1);
    Graph<T, true> G1(N);
    vc<int> par(N, -1);
    auto dfs = [&](auto& dfs, int v) -> void {
      for (auto& e : (*this)[v]) {
        if (e.to == par[v]) continue;
        par[e.to] = v, dfs(dfs, e.to);
      }
    };
    dfs(dfs, root);
    for (auto& e : edges) {
      int a = e.frm, b = e.to;
      if (par[a] == b) swap(a, b);
      assert(par[b] == a);
      G1.add(a, b, e.cost);
    }
    G1.build();
    return G1;
  }

  int get_eid(u64 a, u64 b) const {
    if (len(MP_FOR_EID) == 0) {
      MP_FOR_EID.build(N - 1);
      for (auto& e : edges) {
        u64 a = e.frm, b = e.to;
        u64 k = to_eid_key(a, b);
        MP_FOR_EID[k] = e.id;
      }
    }
    return MP_FOR_EID.get(to_eid_key(a, b), -1);
  }

  u64 to_eid_key(u64 a, u64 b) const {
    if (!directed && a > b) swap(a, b);
    return N * a + b;
  }

 private:
  void calc_deg() const {
    assert(vc_deg.empty());
    vc_deg.resize(N);
    for (auto&& e : edges) vc_deg[e.frm]++, vc_deg[e.to]++;
  }

  void calc_deg_inout() const {
    assert(vc_indeg.empty());
    vc_indeg.resize(N);
    vc_outdeg.resize(N);
    for (auto&& e : edges) {
      vc_indeg[e.to]++, vc_outdeg[e.frm]++;
    }
  }
};
#line 3 "graph/tree.hpp"

// HLD euler tour をとっていろいろ
// HLD=false: 入力辺順で preorder
template <typename GT, bool HLD = true>
struct Tree {
  using Graph_type = GT;
  using WT = typename GT::cost_type;
  int N = 0;
  vector<int> LID, RID, head, V, parent, VtoE, EtoV;
  vc<int> depth;
  vc<WT> depth_weighted;
  vc<int> memo_tail;

  Tree() = default;
  Tree(const GT &G, int r = 0) { build(G, r); }

  void build(const GT &G, int r = 0) {
    N = G.N;
    assert(G.is_prepared());
    assert(G.M == N - 1);
    FOR(i, N - 1) assert(G.edges[i].id == i);
    assert(0 <= r && r < N);
    if constexpr (!HLD)
      build_simple(G, r);
    else
      build_HLD(G, r);
  }

  vc<int> heavy_path_at(int v) const {
    static_assert(HLD);
    assert(head[v] == v);
    int k = LID[v];
    vc<int> P;
    while (k < N && head[V[k]] == v) P.eb(V[k++]);
    return P;
  }

  int heavy_child(int v) const {
    static_assert(HLD);
    if (RID[v] == LID[v] + 1) return -1;
    return V[LID[v] + 1];
  }

  int tail(int v) {
    static_assert(HLD);
    if (memo_tail.empty()) {
      memo_tail.assign(N, -1);
      FOR_R(i, N) {
        int v = V[i];
        int w = heavy_child(v);
        memo_tail[v] = (w == -1 ? v : memo_tail[w]);
      }
    }
    return memo_tail[v];
  }

  int e_to_v(int eid) const { return EtoV[eid]; }
  int v_to_e(int v) const { return VtoE[v]; }
  int get_eid(int u, int v) const {
    if (parent[u] != v) swap(u, v);
    assert(parent[u] == v);
    return VtoE[u];
  }

  int ELID(int v) const { return 2 * LID[v] - depth[v]; }
  int ERID(int v) const { return 2 * RID[v] - depth[v] - 1; }

  // 目標地点へ進む個数が k
  int LA(int v, int k) const {
    static_assert(HLD);
    assert(k <= depth[v]);
    while (1) {
      int u = head[v];
      if (LID[v] - k >= LID[u]) return V[LID[v] - k];
      k -= LID[v] - LID[u] + 1;
      v = parent[u];
    }
  }

  int LCA(int u, int v) const {
    static_assert(HLD);
    for (;; v = parent[head[v]]) {
      if (LID[u] > LID[v]) swap(u, v);
      if (head[u] == head[v]) return u;
    }
  }

  int meet(int a, int b, int c) const {
    static_assert(HLD);
    return LCA(a, b) ^ LCA(a, c) ^ LCA(b, c);
  }

  int subtree_size(int v) const { return RID[v] - LID[v]; }

  int subtree_size(int v, int root) const {
    static_assert(HLD);
    if (v == root) return N;
    int x = jump(v, root, 1);
    if (in_subtree(v, x)) return RID[v] - LID[v];
    return N - RID[x] + LID[x];
  }

  int dist(int a, int b) const {
    static_assert(HLD);
    int c = LCA(a, b);
    return depth[a] + depth[b] - 2 * depth[c];
  }

  WT dist_weighted(int a, int b) const {
    static_assert(HLD);
    int c = LCA(a, b);
    return depth_weighted[a] + depth_weighted[b] - WT(2) * depth_weighted[c];
  }

  // a is in b
  bool in_subtree(int a, int b) const {
    return LID[b] <= LID[a] && LID[a] < RID[b];
  }

  int jump(int a, int b, ll k) const {
    static_assert(HLD);
    if (k == 1) {
      if (a == b) return -1;
      return (in_subtree(b, a) ? LA(b, depth[b] - depth[a] - 1) : parent[a]);
    }
    int c = LCA(a, b);
    int d_ac = depth[a] - depth[c];
    int d_bc = depth[b] - depth[c];
    if (k > d_ac + d_bc) return -1;
    if (k <= d_ac) return LA(a, k);
    return LA(b, d_ac + d_bc - k);
  }

  vc<int> collect_child(int v) const {
    vc<int> res;
    for (int k = LID[v] + 1; k < RID[v];) {
      res.eb(V[k]), k = RID[V[k]];
    }
    return res;
  }

  vc<int> collect_subtree(int v) const {
    return {V.begin() + LID[v], V.begin() + RID[v]};
  }

  vc<int> collect_light(int v) const {
    static_assert(HLD);
    vc<int> res;
    for (int k = LID[v] + 1; k < RID[v];) {
      if (head[V[k]] == V[k]) res.eb(V[k]);
      k = RID[V[k]];
    }
    return res;
  }

  vc<pair<int, int>> get_path_decomposition(int u, int v, bool edge) const {
    static_assert(HLD);
    // [始点, 終点] の"閉"区間列。
    vc<pair<int, int>> up, down;
    while (1) {
      if (head[u] == head[v]) break;
      if (LID[u] < LID[v]) {
        down.eb(LID[head[v]], LID[v]);
        v = parent[head[v]];
      } else {
        up.eb(LID[u], LID[head[u]]);
        u = parent[head[u]];
      }
    }
    if (LID[u] < LID[v]) down.eb(LID[u] + edge, LID[v]);
    elif (LID[v] + edge <= LID[u]) up.eb(LID[u], LID[v] + edge);
    reverse(all(down));
    up.insert(up.end(), all(down));
    return up;
  }

  // 辺の列の情報 (frm,to,str)
  // str = "heavy_up", "heavy_down", "light_up", "light_down"
  vc<tuple<int, int, string>> get_path_decomposition_detail(
      int u, int v) const {
    static_assert(HLD);
    vc<tuple<int, int, string>> up, down;
    while (1) {
      if (head[u] == head[v]) break;
      if (LID[u] < LID[v]) {
        if (v != head[v]) down.eb(head[v], v, "heavy_down"), v = head[v];
        down.eb(parent[v], v, "light_down"), v = parent[v];
      } else {
        if (u != head[u]) up.eb(u, head[u], "heavy_up"), u = head[u];
        up.eb(u, parent[u], "light_up"), u = parent[u];
      }
    }
    if (LID[u] < LID[v]) down.eb(u, v, "heavy_down");
    elif (LID[v] < LID[u]) up.eb(u, v, "heavy_up");
    reverse(all(down));
    concat(up, down);
    return up;
  }

  vc<int> restore_path(int u, int v) const {
    vc<int> L, R;
    while (depth[u] > depth[v]) L.eb(u), u = parent[u];
    while (depth[u] < depth[v]) R.eb(v), v = parent[v];
    while (u != v) L.eb(u), R.eb(v), u = parent[u], v = parent[v];
    L.eb(u);
    while (len(R)) L.eb(POP(R));
    return L;
  }

  // path [a,b] と [c,d] の交わり. 空ならば {-1,-1}.
  // https://codeforces.com/problemset/problem/500/G
  pair<int, int> path_intersection(int a, int b, int c, int d) const {
    static_assert(HLD);
    int ab = LCA(a, b), ac = LCA(a, c), ad = LCA(a, d);
    int bc = LCA(b, c), bd = LCA(b, d), cd = LCA(c, d);
    int x = ab ^ ac ^ bc, y = ab ^ ad ^ bd;  // meet(a,b,c), meet(a,b,d)
    if (x != y) return {x, y};
    int z = ac ^ ad ^ cd;
    if (x != z) x = -1;
    return {x, x};
  }

  // uv path 上で check(v) を満たす最後の v
  // なければ (つまり check(v) が ng )-1
  template <class F>
  int max_path(F check, int u, int v) const {
    static_assert(HLD);
    if (!check(u)) return -1;
    auto pd = get_path_decomposition(u, v, false);
    for (auto [a, b] : pd) {
      if (!check(V[a])) return u;
      if (check(V[b])) {
        u = V[b];
        continue;
      }
      int c =
          binary_search([&](int c) -> bool { return check(V[c]); }, a, b, 0);
      return V[c];
    }
    return u;
  }

 private:
  void build_simple(const GT &G, int r = 0) {
    N = G.N;
    LID.assign(N, 0), RID.assign(N, 0);
    V.assign(N, -1), parent.assign(N, -1), VtoE.assign(N, -1),
        EtoV.assign(N - 1, -1);
    depth.assign(N, 0), depth_weighted.assign(N, 0);

    // 1st dfs.
    int k = 0;
    vc<int> st;
    st.reserve(N);
    st.eb(r);
    while (len(st)) {
      int v = POP(st);
      LID[v] = k, V[k] = v;
      ++k;
      for (int i = G.indptr[v + 1] - 1; i >= G.indptr[v]; --i) {
        auto &e = G.csr_edges[i];
        if (e.to == parent[v]) continue;
        parent[e.to] = v;
        depth[e.to] = depth[v] + 1;
        depth_weighted[e.to] = depth_weighted[v] + e.cost;
        VtoE[e.to] = e.id, EtoV[e.id] = e.to;
        st.eb(e.to);
      }
    }

    FOR_R(i, N) {
      int v = V[i];
      chmax(RID[v], LID[v] + 1);
      if (parent[v] != -1) chmax(RID[parent[v]], RID[v]);
    }
  }

  void build_HLD(const GT &G, int r = 0) {
    N = G.N;
    LID.assign(N, 0), RID.assign(N, 0), head.assign(N, r);
    V.assign(N, -1), parent.assign(N, -1), VtoE.assign(N, -1),
        EtoV.assign(N - 1, -1);
    depth.assign(N, 0), depth_weighted.assign(N, 0);
    memo_tail.clear();

    // 1st dfs.
    {
      int k = 0;
      vc<int> st;
      st.reserve(N);
      st.eb(r);
      while (len(st)) {
        int v = POP(st);
        V[k++] = v;
        for (auto &e : G[v]) {
          if (e.to == parent[v]) continue;
          parent[e.to] = v, st.eb(e.to), depth[e.to] = depth[v] + 1;
          depth_weighted[e.to] = depth_weighted[v] + e.cost;
          VtoE[e.to] = e.id, EtoV[e.id] = e.to;
        }
      }
      // 一時的に RID[v] := sz[v]
      FOR_R(i, N) {
        int v = V[i];
        RID[v] += 1;
        if (parent[v] != -1) RID[parent[v]] += RID[v];
      }
    }
    // 2nd dfs.
    {
      int k = 0;
      vc<int> st;
      st.reserve(N);
      st.eb(r);
      while (len(st)) {
        int v = POP(st);
        V[k] = v, LID[v] = k;
        RID[v] = k + RID[v];
        ++k;
        int max_sz = 0, max_ch = -1;
        for (auto &e : G[v]) {
          if (e.to == parent[v]) continue;
          if (chmax(max_sz, RID[e.to])) max_ch = e.to;
        }
        for (int i = G.indptr[v + 1] - 1; i >= G.indptr[v]; --i) {
          auto &e = G.csr_edges[i];
          if (e.to == parent[v] || e.to == max_ch) continue;
          st.eb(e.to), head[e.to] = e.to;
        }
        if (max_ch != -1) st.eb(max_ch), head[max_ch] = head[v];
      }
    }
  }
};
#line 1 "ds/unionfind/unionfind.hpp"

struct UnionFind {
  int n, n_comp;
  vc<int> dat; // par or (-size)
  UnionFind(int n = 0) { build(n); }

  void build(int m) {
    n = m, n_comp = m;
    dat.assign(n, -1);
  }

  void reset() { build(n); }

  int operator[](int x) {
    while (dat[x] >= 0) {
      int pp = dat[dat[x]];
      if (pp < 0) { return dat[x]; }
      x = dat[x] = pp;
    }
    return x;
  }

  ll size(int x) {
    x = (*this)[x];
    return -dat[x];
  }

  bool merge(int x, int y) {
    x = (*this)[x], y = (*this)[y];
    if (x == y) return false;
    if (-dat[x] < -dat[y]) swap(x, y);
    dat[x] += dat[y], dat[y] = x, n_comp--;
    return true;
  }

  vc<int> get_all() {
    vc<int> A(n);
    FOR(i, n) A[i] = (*this)[i];
    return A;
  }
};
#line 11 "test/3_yukicoder/1600_2.test.cpp"

#line 1 "mod/modint_common.hpp"

#line 1 "other/bit.hpp"

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
int popcnt_sgn(int x) { return (__builtin_parity(unsigned(x)) & 1 ? -1 : 1); }
int popcnt_sgn(u32 x) { return (__builtin_parity(x) & 1 ? -1 : 1); }
int popcnt_sgn(ll x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
int popcnt_sgn(u64 x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T kth_bit(int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return T(1) << k;
}
template <typename T>
bool has_kth_bit(T x, int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return x >> k & 1;
}

template <typename UINT>
struct all_bit {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_bit(UINT s) : s(s) {}
  struct iter {
    UINT s;
    int operator*() const { return lowbit(s); }
    void operator++() { s &= s - 1; }
    bool operator!=(nullptr_t) const { return s; }
  };
  iter begin() const { return {s}; }
  nullptr_t end() const { return nullptr; }
};

template <typename UINT>
struct all_subset {
  static_assert(is_unsigned<UINT>::value);
  UINT s;
  all_subset(UINT s) : s(s) {}
  struct iter {
    UINT s, t;
    bool done = false;
    UINT operator*() const { return t; }
    void operator++() {
      done = (t == 0);
      t = (t - 1) & s;
    }
    bool operator!=(nullptr_t) const { return !done; }
  };
  iter begin() const { return {s, s}; }
  nullptr_t end() const { return nullptr; }
};

constexpr u64 full_mask(int n) {
  assert(0 <= n && n <= 64);
  return n == 64 ? -1ULL : (1ULL << n) - 1;
}

u64 bit_reverse(u64 x) {
  x = ((x & 0x5555555555555555ULL) << 1) | ((x >> 1) & 0x5555555555555555ULL);
  x = ((x & 0x3333333333333333ULL) << 2) | ((x >> 2) & 0x3333333333333333ULL);
  x = ((x & 0x0f0f0f0f0f0f0f0fULL) << 4) | ((x >> 4) & 0x0f0f0f0f0f0f0f0fULL);
  x = ((x & 0x00ff00ff00ff00ffULL) << 8) | ((x >> 8) & 0x00ff00ff00ff00ffULL);
  x = ((x & 0x0000ffff0000ffffULL) << 16) | ((x >> 16) & 0x0000ffff0000ffffULL);
  x = (x << 32) | (x >> 32);
  return x;
}
#line 3 "mod/modint_common.hpp"

struct has_mod_impl {
  template <class T>
  static auto check(T &&x) -> decltype(x.get_mod(), std::true_type{});
  template <class T>
  static auto check(...) -> std::false_type;
};

template <class T>
class has_mod : public decltype(has_mod_impl::check<T>(std::declval<T>())) {};

template <typename mint>
mint fact(int n) {
  static vector<mint> dat = {1, 1};
  static int mod = 0;
  if (mod != mint::get_mod()) {
    mod = mint::get_mod();
    dat = {1, 1};
  }
  assert(0 <= n && n < mod);
  if (len(dat) <= n) {
    int now = len(dat);
    int m = min(mod, 1 << (topbit(n) + 1));
    dat.resize(m);
    FOR(i, now, m) dat[i] = dat[i - 1] * mint::raw(i);
  }
  return dat[n];
}

template <typename mint>
mint fact_inv(int n) {
  if (n < 0) return mint(0);
  static vector<mint> dat = {1, 1};
  static int mod = 0;
  if (mod != mint::get_mod()) {
    mod = mint::get_mod();
    dat = {1, 1};
  }
  assert(0 <= n && n < mod);
  if (len(dat) <= n) {
    int now = len(dat);
    int m = min(mod, 1 << (topbit(n) + 1));
    dat.resize(m);
    dat[m - 1] = fact<mint>(m - 1).inverse();
    FOR_R(i, now, m - 1) dat[i] = dat[i + 1] * mint::raw(i + 1);
  }
  return dat[n];
}

template <class mint, class... Ts>
mint fact_invs(Ts... xs) {
  return (mint(1) * ... * fact_inv<mint>(xs));
}

template <typename mint>
mint inv(int n) {
  return fact<mint>(n - 1) * fact_inv<mint>(n);
}

template <>
double inv<double>(int n) {
  assert(n != 0);
  return 1.0 / n;
}

template <typename mint, class Head, class... Tail>
mint multinomial(Head &&head, Tail &&...tail) {
  return fact<mint>(head) * fact_invs<mint>(std::forward<Tail>(tail)...);
}

template <typename mint>
mint C_dense(int n, int k) {
  assert(n >= 0);
  if (k < 0 || n < k) return 0;
  static vvc<mint> C;
  static int H = 0, W = 0;
  static int mod = 0;
  if (mod != mint::get_mod()) {
    mod = mint::get_mod();
    C.clear();
    H = W = 0;
  }
  auto calc = [&](int i, int j) -> mint {
    if (i == 0) return (j == 0 ? mint(1) : mint(0));
    return C[i - 1][j] + (j ? C[i - 1][j - 1] : 0);
  };
  if (W <= k) {
    FOR(i, H) {
      C[i].resize(k + 1);
      FOR(j, W, k + 1) { C[i][j] = calc(i, j); }
    }
    W = k + 1;
  }
  if (H <= n) {
    C.resize(n + 1);
    FOR(i, H, n + 1) {
      C[i].resize(W);
      FOR(j, W) { C[i][j] = calc(i, j); }
    }
    H = n + 1;
  }
  return C[n][k];
}

template <typename mint, bool large = false, bool dense = false>
mint C(ll n, ll k) {
  assert(n >= 0);
  if (k < 0 || n < k) return 0;
  if constexpr (dense) return C_dense<mint>(n, k);
  if constexpr (!large) return multinomial<mint>(n, k, n - k);
  k = min(k, n - k);
  mint x(1);
  FOR(i, k) x *= mint(n - i);
  return x * fact_inv<mint>(k);
}

template <typename mint, bool large = false>
mint C_inv(ll n, ll k) {
  assert(n >= 0);
  assert(0 <= k && k <= n);
  if (!large) return fact_inv<mint>(n) * fact<mint>(k) * fact<mint>(n - k);
  return mint(1) / C<mint, 1>(n, k);
}

// [x^d](1-x)^{-n}
template <typename mint, bool large = false, bool dense = false>
mint C_negative(ll n, ll d) {
  assert(n >= 0);
  if (d < 0) return mint(0);
  if (n == 0) {
    return (d == 0 ? mint(1) : mint(0));
  }
  return C<mint, large, dense>(n + d - 1, d);
}
#line 2 "mod/modint.hpp"

template <int mod>
struct modint {
  static constexpr u32 umod = u32(mod);
  static_assert(0 < umod && umod < u32(1) << 31);
  u32 val;

  static modint raw(u32 v) {
    modint x;
    x.val = v;
    return x;
  }
  constexpr modint() : val(0) {}
  constexpr modint(u32 x) : val(x % umod) {}
  constexpr modint(u64 x) : val(x % umod) {}
  constexpr modint(u128 x) : val(x % umod) {}
  constexpr modint(int x) : val((x %= mod) < 0 ? x + mod : x){};
  constexpr modint(ll x) : val((x %= mod) < 0 ? x + mod : x){};
  constexpr modint(i128 x) : val((x %= mod) < 0 ? x + mod : x){};
  bool operator<(const modint &other) const { return val < other.val; }
  modint &operator+=(const modint &p) {
    if ((val += p.val) >= umod) val -= umod;
    return *this;
  }
  modint &operator-=(const modint &p) {
    if ((val += umod - p.val) >= umod) val -= umod;
    return *this;
  }
  modint &operator*=(const modint &p) {
    val = u64(val) * p.val % umod;
    return *this;
  }
  modint &operator/=(const modint &p) {
    *this *= p.inverse();
    return *this;
  }
  modint operator-() const { return modint::raw(val ? mod - val : u32(0)); }
  modint operator+(const modint &p) const { return modint(*this) += p; }
  modint operator-(const modint &p) const { return modint(*this) -= p; }
  modint operator*(const modint &p) const { return modint(*this) *= p; }
  modint operator/(const modint &p) const { return modint(*this) /= p; }
  bool operator==(const modint &p) const { return val == p.val; }
  bool operator!=(const modint &p) const { return val != p.val; }
  modint inverse() const {
    int a = val, b = mod, u = 1, v = 0, t;
    while (b > 0) {
      t = a / b;
      swap(a -= t * b, b), swap(u -= t * v, v);
    }
    return modint(u);
  }
  modint pow(ll n) const {
    if (n < 0) return inverse().pow(-n);
    assert(n >= 0);
    modint ret(1), mul(val);
    while (n > 0) {
      if (n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }
  static constexpr int get_mod() { return mod; }
  // (n, r), r は 1 の 2^n 乗根
  static constexpr pair<int, int> ntt_info() {
    if (mod == 120586241) return {20, 74066978};
    if (mod == 167772161) return {25, 17};
    if (mod == 469762049) return {26, 30};
    if (mod == 754974721) return {24, 362};
    if (mod == 880803841) return {23, 211};
    if (mod == 943718401) return {22, 663003469};
    if (mod == 998244353) return {23, 31};
    if (mod == 1004535809) return {21, 582313106};
    if (mod == 1012924417) return {21, 368093570};
    if (mod == 1224736769) return {24, 1191450770};
    if (mod == 2013265921) return {27, 244035102};
    return {-1, -1};
  }
  static constexpr bool can_ntt() { return ntt_info().fi != -1; }
};

#ifdef FASTIO
template <int mod>
void rd(modint<mod> &x) {
  fastio::rd(x.val);
  x.val %= mod;
  // assert(0 <= x.val && x.val < mod);
}
template <int mod>
void wt(modint<mod> x) {
  fastio::wt(x.val);
}
#endif

using modint107 = modint<1000000007>;
using modint998 = modint<998244353>;
#line 13 "test/3_yukicoder/1600_2.test.cpp"
using mint = modint107;

void solve() {
  LL(N, M);
  Graph<mint, 0> G(N);
  UnionFind uf(N);
  vc<pair<int, int>> edges;
  vc<bool> in_G(M);
  mint wt = 1;
  FOR(i, M) {
    LL(a, b);
    --a, --b;
    edges.eb(a, b);
    wt += wt;
    if (uf.merge(a, b)) {
      in_G[i] = 1;
      G.add(a, b, wt);
    }
  }
  G.build();

  Tree<decltype(G)> tree(G);
  auto& par = tree.parent;
  vc<int> X, Y, W;
  FOR(e, M) {
    if (in_G[e]) continue;
    auto [a, b] = edges[e];
    a = tree.LID[a], b = tree.LID[b];
    if (a > b) swap(a, b);
    X.eb(a), Y.eb(b), W.eb(e);
  }

  using Mono = Monoid_Min<int>;
  using ST = Sparse_Table<Mono>;
  Wavelet_Matrix_2D_Range<int, false, false, Static_Range_Product<Mono, ST>>
      seg(len(X),
          [&](int i) -> tuple<int, int, int> { return {X[i], Y[i], W[i]}; });

  LL(Q);
  FOR(Q) {
    LL(u, v, idx);
    --u, --v, --idx;
    auto [x, y] = edges[idx];
    if (par[y] == x) swap(x, y);
    bool in_u = tree.in_subtree(u, x);
    bool in_v = tree.in_subtree(v, x);
    if (!in_G[idx] || in_u == in_v) {
      print(tree.dist_weighted(u, v));
      continue;
    }
    // 木の外に出る移動が必要
    int l = tree.LID[x], r = tree.RID[x];
    int min_i = Mono::op(seg.prod(0, l, l, r), seg.prod(l, r, r, N));
    if (min_i == Mono::id()) {
      print(-1);
      continue;
    }
    auto [p, q] = edges[min_i];
    bool in_p = tree.in_subtree(p, x);
    if (!in_u) swap(u, v);
    if (!in_p) swap(p, q);
    mint ANS = tree.dist_weighted(u, p) + tree.dist_weighted(v, q);
    ANS += mint(2).pow(min_i + 1);
    print(ANS);
  }
}

signed main() {
  solve();
  return 0;
}
Back to top page