結果

問題 No.1094 木登り / Climbing tree
ユーザー iiljjiiljj
提出日時 2020-06-25 00:42:30
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 475 ms / 2,000 ms
コード長 9,687 bytes
コンパイル時間 3,467 ms
コンパイル使用メモリ 214,488 KB
実行使用メモリ 54,188 KB
最終ジャッジ日時 2023-08-08 00:22:17
合計ジャッジ時間 15,795 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 464 ms
50,708 KB
testcase_02 AC 118 ms
54,188 KB
testcase_03 AC 47 ms
6,756 KB
testcase_04 AC 104 ms
22,800 KB
testcase_05 AC 211 ms
42,480 KB
testcase_06 AC 146 ms
19,164 KB
testcase_07 AC 475 ms
51,164 KB
testcase_08 AC 456 ms
50,952 KB
testcase_09 AC 460 ms
50,716 KB
testcase_10 AC 465 ms
50,712 KB
testcase_11 AC 461 ms
50,712 KB
testcase_12 AC 454 ms
50,760 KB
testcase_13 AC 473 ms
50,728 KB
testcase_14 AC 461 ms
50,840 KB
testcase_15 AC 137 ms
17,132 KB
testcase_16 AC 315 ms
45,044 KB
testcase_17 AC 219 ms
28,964 KB
testcase_18 AC 177 ms
23,284 KB
testcase_19 AC 296 ms
38,156 KB
testcase_20 AC 465 ms
50,700 KB
testcase_21 AC 217 ms
30,564 KB
testcase_22 AC 452 ms
50,760 KB
testcase_23 AC 440 ms
50,748 KB
testcase_24 AC 454 ms
50,752 KB
testcase_25 AC 453 ms
50,740 KB
testcase_26 AC 461 ms
50,704 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

/* #region Head */

#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pll = pair<ll, ll>;
template <class T> using vc = vector<T>;
template <class T> using vvc = vc<vc<T>>;
using vll = vc<ll>;
using vvll = vvc<ll>;
using vld = vc<ld>;
using vvld = vvc<ld>;
using vs = vc<string>;
using vvs = vvc<string>;
template <class T, class U> using um = unordered_map<T, U>;
template <class T> using pq = priority_queue<T>;
template <class T> using pqa = priority_queue<T, vc<T>, greater<T>>;
template <class T> using us = unordered_set<T>;

#define REP(i, m, n) for (ll i = (m), i##_len = (ll)(n); i < i##_len; ++(i))
#define REPM(i, m, n) for (ll i = (m), i##_max = (ll)(n); i <= i##_max; ++(i))
#define REPR(i, m, n) for (ll i = (m), i##_min = (ll)(n); i >= i##_min; --(i))
#define REPD(i, m, n, d) for (ll i = (m), i##_len = (ll)(n); i < i##_len; i += (d))
#define REPMD(i, m, n, d) for (ll i = (m), i##_max = (ll)(n); i <= i##_max; i += (d))
#define REPI(itr, ds) for (auto itr = ds.begin(); itr != ds.end(); itr++)
#define ALL(x) begin(x), end(x)
#define SIZE(x) ((ll)(x).size())
#define PERM(c)                                                                                                        \
    sort(ALL(c));                                                                                                      \
    for (bool c##p = 1; c##p; c##p = next_permutation(ALL(c)))
#define UNIQ(v) v.erase(unique(ALL(v)), v.end());

#define endl '\n'
#define sqrt sqrtl
#define floor floorl
#define log2 log2l

constexpr ll INF = 1'010'000'000'000'000'017LL;
constexpr ll MOD = 1'000'000'007LL; // 1e9 + 7
constexpr ld EPS = 1e-12;
constexpr ld PI = 3.14159265358979323846;

template <typename T> istream &operator>>(istream &is, vc<T> &vec) { // vector 入力
    for (T &x : vec) is >> x;
    return is;
}
template <typename T> ostream &operator<<(ostream &os, vc<T> &vec) { // vector 出力 (for dump)
    os << "{";
    REP(i, 0, SIZE(vec)) os << vec[i] << (i == i_len - 1 ? "" : ", ");
    os << "}";
    return os;
}
template <typename T> ostream &operator>>(ostream &os, vc<T> &vec) { // vector 出力 (inline)
    REP(i, 0, SIZE(vec)) os << vec[i] << (i == i_len - 1 ? "\n" : " ");
    return os;
}

template <typename T, typename U> istream &operator>>(istream &is, pair<T, U> &pair_var) { // pair 入力
    is >> pair_var.first >> pair_var.second;
    return is;
}
template <typename T, typename U> ostream &operator<<(ostream &os, pair<T, U> &pair_var) { // pair 出力
    os << "(" << pair_var.first << ", " << pair_var.second << ")";
    return os;
}

// map, um, set, us 出力
template <class T> ostream &out_iter(ostream &os, T &map_var) {
    os << "{";
    REPI(itr, map_var) {
        os << *itr;
        auto itrcp = itr;
        if (++itrcp != map_var.end()) os << ", ";
    }
    return os << "}";
}
template <typename T, typename U> ostream &operator<<(ostream &os, map<T, U> &map_var) { return out_iter(os, map_var); }
template <typename T, typename U> ostream &operator<<(ostream &os, um<T, U> &map_var) {
    os << "{";
    REPI(itr, map_var) {
        auto [key, value] = *itr;
        os << "(" << key << ", " << value << ")";
        auto itrcp = itr;
        if (++itrcp != map_var.end()) os << ", ";
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, set<T> &set_var) { return out_iter(os, set_var); }
template <typename T> ostream &operator<<(ostream &os, us<T> &set_var) { return out_iter(os, set_var); }
template <typename T> ostream &operator<<(ostream &os, pq<T> &pq_var) {
    pq<T> pq_cp(pq_var);
    os << "{";
    if (!pq_cp.empty()) {
        os << pq_cp.top(), pq_cp.pop();
        while (!pq_cp.empty()) os << ", " << pq_cp.top(), pq_cp.pop();
    }
    return os << "}";
}

// dump
#define DUMPOUT cerr
void dump_func() { DUMPOUT << endl; }
template <class Head, class... Tail> void dump_func(Head &&head, Tail &&... tail) {
    DUMPOUT << head;
    if (sizeof...(Tail) > 0) DUMPOUT << ", ";
    dump_func(move(tail)...);
}

// chmax (更新「される」かもしれない値が前)
template <typename T, typename U, typename Comp = less<>> bool chmax(T &xmax, const U &x, Comp comp = {}) {
    if (comp(xmax, x)) {
        xmax = x;
        return true;
    }
    return false;
}

// chmin (更新「される」かもしれない値が前)
template <typename T, typename U, typename Comp = less<>> bool chmin(T &xmin, const U &x, Comp comp = {}) {
    if (comp(x, xmin)) {
        xmin = x;
        return true;
    }
    return false;
}

// ローカル用
#define DEBUG_

#ifdef DEBUG_
#define DEB
#define dump(...)                                                                                                      \
    DUMPOUT << "  " << string(#__VA_ARGS__) << ": "                                                                    \
            << "[" << to_string(__LINE__) << ":" << __FUNCTION__ << "]" << endl                                        \
            << "    ",                                                                                                 \
        dump_func(__VA_ARGS__)
#else
#define DEB if (false)
#define dump(...)
#endif

struct AtCoderInitialize {
    static constexpr int IOS_PREC = 15;
    static constexpr bool AUTOFLUSH = false;
    AtCoderInitialize() {
        ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
        cout << fixed << setprecision(IOS_PREC);
        if (AUTOFLUSH) cout << unitbuf;
    }
} ATCODER_INITIALIZE;

void Yn(bool p) { cout << (p ? "Yes" : "No") << endl; }
void YN(bool p) { cout << (p ? "YES" : "NO") << endl; }

/* #endregion */

/* #region Graph */

// エッジ(本来エッジは双方向だが,ここでは単方向で管理)
template <class weight_t, class flow_t> struct Edge {
    ll src;          // エッジ始点となる頂点
    ll dst;          // エッジ終点となる頂点
    weight_t weight; // 重み
    flow_t cap;
    Edge() : src(0), dst(0), weight(0) {}
    Edge(ll src, ll dst, weight_t weight) : src(src), dst(dst), weight(weight) {}
    Edge(ll src, ll dst, weight_t weight, flow_t cap) : src(src), dst(dst), weight(weight), cap(cap) {}
    // Edge 標準出力
    friend ostream &operator<<(ostream &os, Edge &edge) {
        os << "(" << edge.src << " -> " << edge.dst << ", " << edge.weight << ")";
        return os;
    }
};
// 同じ頂点を始点とするエッジ集合
template <class weight_t, class flow_t> class Node : public vc<Edge<weight_t, flow_t>> {
  public:
    ll idx;
    Node() : vc<Edge<weight_t, flow_t>>() {}
    // void add(int a, int b, weight_t w, flow_t cap) { this->emplace_back(a, b, w, cap); };
};
// graph[i] := 頂点 i を始点とするエッジ集合
template <class weight_t, class flow_t> class Graph : public vc<Node<weight_t, flow_t>> {
  public:
    Graph() : vc<Node<weight_t, flow_t>>() {}
    Graph(int n) : vc<Node<weight_t, flow_t>>(n) { REP(i, 0, n)(*this)[i].idx = i; }
    // 単方向
    void add_arc(int a, int b, weight_t w = 1, flow_t cap = 1) { (*this)[a].emplace_back(a, b, w, cap); }
    // 双方向
    void add_edge(int a, int b, weight_t w = 1, flow_t cap = 1) { add_arc(a, b, w, cap), add_arc(b, a, w, cap); }
};
// using Array = vc<Weight>;
// using Matrix = vc<Array>;

/* #endregion */

/* #region LCA */

template <class weight_t, class flow_t> class LCA {
  public:
    const int n = 0;
    const int log2_n = 0;
    vc<vc<int>> parent;
    vc<int> depth;
    using G = Graph<weight_t, flow_t>;

    LCA() {}

    // コンストラクタ,前処理 O(N log N)
    LCA(const G &g, int root) : n(g.size()), log2_n(log2(n) + 1), parent(log2_n, vc<int>(n)), depth(n) {
        dfs(g, root, -1, 0);
        REP(k, 0, log2_n - 1) REP(v, 0, SIZE(g)) parent[k + 1][v] = (parent[k][v] < 0) ? -1 : parent[k][parent[k][v]];
    }

    // 根からの距離と1つ先の頂点を求める
    void dfs(const G &g, int v, int p, int d) {
        parent[0][v] = p, depth[v] = d;
        for (const Edge<weight_t, flow_t> &e : g[v])
            if (e.dst != p) dfs(g, e.dst, v, d + 1);
    }

    // 頂点 u, v の LCA を求めて返す,O(log N)
    int get(int u, int v) {
        if (depth[u] > depth[v]) std::swap(u, v);
        // 深い方を浅い方と同じ浅さまで移動することで,LCA までの深さを同じにする
        REP(k, 0, log2_n) if ((depth[v] - depth[u]) >> k & 1) v = parent[k][v];
        if (u == v) return u;

        // 二分探索で LCA を求める
        REPR(k, log2_n - 1, 0) if (parent[k][u] != parent[k][v]) u = parent[k][u], v = parent[k][v];
        return parent[0][u];
    }
};

/* #endregion */

// Problem
void solve() {
    ll n;
    cin >> n;

    vll a(n - 1), b(n - 1), c(n - 1);
    REP(i, 0, n - 1) {
        cin >> a[i] >> b[i] >> c[i];
        --a[i], --b[i];
    }

    ll q;
    cin >> q;
    vll s(q), t(q);
    REP(i, 0, q) {
        cin >> s[i] >> t[i];
        --s[i], --t[i];
    }

    Graph<ll, ll> graph(n);
    REP(i, 0, n - 1) graph.add_edge(a[i], b[i], c[i]);

    vll depth(n);
    auto dfs_depth = [&](auto &&dfs_depth, int idx, int par, ll d) -> void {
        depth[idx] = d;
        for (Edge<ll, ll> &e : graph[idx]) {
            if (e.dst != par) dfs_depth(dfs_depth, e.dst, idx, d + e.weight);
        }
    };
    dfs_depth(dfs_depth, 0, -1, 0);

    LCA<ll, ll> lca(graph, 0);
    auto f = [&](ll a, ll b) -> ll {
        ll lcaidx = lca.get(a, b);
        return depth[a] + depth[b] - 2 * depth[lcaidx];
    };

    REP(i, 0, q) cout << f(s[i], t[i]) << endl;
}

// entry point
int main() {
    solve();
    return 0;
}
0