結果

問題 No.1789 Tree Growing
ユーザー hitonanodehitonanode
提出日時 2021-12-18 01:16:31
言語 C++23
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 18,348 bytes
コンパイル時間 3,197 ms
コンパイル使用メモリ 224,044 KB
実行使用メモリ 11,096 KB
最終ジャッジ日時 2024-09-15 02:25:17
合計ジャッジ時間 11,209 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,816 KB
testcase_01 AC 2 ms
6,820 KB
testcase_02 AC 2 ms
6,944 KB
testcase_03 AC 2 ms
6,940 KB
testcase_04 AC 3 ms
6,940 KB
testcase_05 AC 2 ms
6,940 KB
testcase_06 AC 2 ms
6,944 KB
testcase_07 AC 3 ms
6,944 KB
testcase_08 AC 1 ms
6,940 KB
testcase_09 AC 2 ms
6,944 KB
testcase_10 AC 2 ms
6,940 KB
testcase_11 AC 3 ms
6,940 KB
testcase_12 AC 2 ms
6,944 KB
testcase_13 AC 2 ms
6,940 KB
testcase_14 AC 2 ms
6,940 KB
testcase_15 AC 3 ms
6,940 KB
testcase_16 AC 3 ms
6,944 KB
testcase_17 AC 4 ms
6,944 KB
testcase_18 AC 3 ms
6,944 KB
testcase_19 AC 3 ms
6,940 KB
testcase_20 AC 4 ms
6,944 KB
testcase_21 AC 9 ms
6,940 KB
testcase_22 AC 6 ms
6,944 KB
testcase_23 AC 6 ms
6,940 KB
testcase_24 AC 6 ms
6,944 KB
testcase_25 AC 13 ms
6,944 KB
testcase_26 AC 13 ms
6,944 KB
testcase_27 AC 12 ms
6,944 KB
testcase_28 AC 11 ms
6,944 KB
testcase_29 AC 13 ms
6,944 KB
testcase_30 AC 15 ms
6,948 KB
testcase_31 AC 17 ms
6,944 KB
testcase_32 AC 15 ms
6,940 KB
testcase_33 AC 16 ms
6,948 KB
testcase_34 AC 17 ms
6,940 KB
testcase_35 AC 14 ms
6,940 KB
testcase_36 AC 19 ms
6,944 KB
testcase_37 AC 18 ms
6,944 KB
testcase_38 AC 17 ms
6,940 KB
testcase_39 AC 14 ms
6,940 KB
testcase_40 AC 17 ms
6,940 KB
testcase_41 AC 18 ms
6,944 KB
testcase_42 AC 19 ms
6,940 KB
testcase_43 AC 20 ms
6,940 KB
testcase_44 AC 19 ms
6,944 KB
testcase_45 AC 18 ms
6,940 KB
testcase_46 AC 16 ms
6,944 KB
testcase_47 AC 13 ms
6,940 KB
testcase_48 AC 7 ms
6,944 KB
testcase_49 AC 17 ms
6,940 KB
testcase_50 AC 16 ms
6,940 KB
testcase_51 AC 6 ms
6,940 KB
testcase_52 AC 18 ms
6,940 KB
testcase_53 AC 7 ms
6,944 KB
testcase_54 AC 12 ms
6,940 KB
testcase_55 AC 13 ms
6,944 KB
testcase_56 AC 12 ms
6,940 KB
testcase_57 AC 17 ms
6,940 KB
testcase_58 AC 12 ms
6,944 KB
testcase_59 AC 14 ms
6,940 KB
testcase_60 TLE -
testcase_61 -- -
testcase_62 -- -
testcase_63 -- -
testcase_64 -- -
testcase_65 -- -
testcase_66 -- -
testcase_67 -- -
testcase_68 -- -
testcase_69 -- -
testcase_70 -- -
testcase_71 -- -
testcase_72 -- -
testcase_73 -- -
testcase_74 -- -
testcase_75 -- -
testcase_76 -- -
testcase_77 -- -
testcase_78 -- -
testcase_79 -- -
testcase_80 -- -
testcase_81 -- -
testcase_82 -- -
testcase_83 -- -
testcase_84 -- -
testcase_85 -- -
testcase_86 -- -
testcase_87 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T, typename V>
void ndarray(vector<T>& vec, const V& val, int len) { vec.assign(len, val); }
template <typename T, typename V, typename... Args> void ndarray(vector<T>& vec, const V& val, int len, Args... args) { vec.resize(len), for_each(begin(vec), end(vec), [&](T& v) { ndarray(v, val, args...); }); }
template <typename T> bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; }
template <typename T> bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; }
int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); }
template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); }
template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); }
template <typename T> vector<T> sort_unique(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <typename T> int arglb(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); }
template <typename T> int argub(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); }
template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; }
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T, size_t sz> ostream &operator<<(ostream &os, const array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
#if __cplusplus >= 201703L
template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
#endif
template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T, typename TH> ostream &operator<<(ostream &os, const unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <typename TK, typename TV, typename TH> ostream &operator<<(ostream &os, const unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef HITONANODE_LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << endl
#define dbgif(cond, x) ((cond) ? cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << endl : cerr)
#else
#define dbg(x) (x)
#define dbgif(cond, x) 0
#endif

#include <atcoder/mincostflow>

// Minimum cost flow WITH NO NEGATIVE CYCLE (just negative cost edge is allowed)
// Verified:
// - SRM 770 Div1 Medium https://community.topcoder.com/stat?c=problem_statement&pm=15702
// - CodeChef LTIME98 Ancient Magic https://www.codechef.com/problems/ANCT
template <class Cap, class Cost, Cost INF_COST = std::numeric_limits<Cost>::max() / 2>
struct MinCostFlow {
    template <class E> struct csr {
        std::vector<int> start;
        std::vector<E> elist;
        explicit csr(int n, const std::vector<std::pair<int, E>> &edges)
            : start(n + 1), elist(edges.size()) {
            for (auto e : edges) { start[e.first + 1]++; }
            for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; }
            auto counter = start;
            for (auto e : edges) { elist[counter[e.first]++] = e.second; }
        }
    };

public:
    MinCostFlow() {}
    explicit MinCostFlow(int n) : is_dual_infeasible(false), _n(n) {
        static_assert(std::numeric_limits<Cap>::max() > 0, "max() must be greater than 0");
    }

    int add_edge(int from, int to, Cap cap, Cost cost) {
        assert(0 <= from && from < _n);
        assert(0 <= to && to < _n);
        assert(0 <= cap);
        if (cost < 0) is_dual_infeasible = true;
        int m = int(_edges.size());
        _edges.push_back({from, to, cap, 0, cost});
        return m;
    }

    struct edge {
        int from, to;
        Cap cap, flow;
        Cost cost;
    };

    edge get_edge(int i) {
        int m = int(_edges.size());
        assert(0 <= i && i < m);
        return _edges[i];
    }
    std::vector<edge> edges() { return _edges; }

    std::pair<Cap, Cost> flow(int s, int t) { return flow(s, t, std::numeric_limits<Cap>::max()); }
    std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) {
        return slope(s, t, flow_limit).back();
    }
    std::vector<std::pair<Cap, Cost>> slope(int s, int t) {
        return slope(s, t, std::numeric_limits<Cap>::max());
    }
    std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) {
        assert(0 <= s && s < _n);
        assert(0 <= t && t < _n);
        assert(s != t);

        int m = int(_edges.size());
        std::vector<int> edge_idx(m);

        auto g = [&]() {
            std::vector<int> degree(_n), redge_idx(m);
            std::vector<std::pair<int, _edge>> elist;
            elist.reserve(2 * m);
            for (int i = 0; i < m; i++) {
                auto e = _edges[i];
                edge_idx[i] = degree[e.from]++;
                redge_idx[i] = degree[e.to]++;
                elist.push_back({e.from, {e.to, -1, e.cap - e.flow, e.cost}});
                elist.push_back({e.to, {e.from, -1, e.flow, -e.cost}});
            }
            auto _g = csr<_edge>(_n, elist);
            for (int i = 0; i < m; i++) {
                auto e = _edges[i];
                edge_idx[i] += _g.start[e.from];
                redge_idx[i] += _g.start[e.to];
                _g.elist[edge_idx[i]].rev = redge_idx[i];
                _g.elist[redge_idx[i]].rev = edge_idx[i];
            }
            return _g;
        }();

        auto result = slope(g, s, t, flow_limit);

        for (int i = 0; i < m; i++) {
            auto e = g.elist[edge_idx[i]];
            _edges[i].flow = _edges[i].cap - e.cap;
        }

        return result;
    }

private:
    bool is_dual_infeasible;
    int _n;
    std::vector<edge> _edges;

    // inside edge
    struct _edge {
        int to, rev;
        Cap cap;
        Cost cost;
    };

    std::vector<std::pair<Cap, Cost>> slope(csr<_edge> &g, int s, int t, Cap flow_limit) {
        // variants (C = maxcost):
        // -(n-1)C <= dual[s] <= dual[i] <= dual[t] = 0
        // reduced cost (= e.cost + dual[e.from] - dual[e.to]) >= 0 for all edge

        // dual_dist[i] = (dual[i], dist[i])
        std::vector<std::pair<Cost, Cost>> dual_dist(_n);
        if (is_dual_infeasible) {
            auto check_dag = [&]() {
                std::vector<int> deg_in(_n);
                for (int v = 0; v < _n; v++) {
                    for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                        deg_in[g.elist[i].to] += g.elist[i].cap > 0;
                    }
                }
                std::vector<int> st;
                st.reserve(_n);
                for (int i = 0; i < _n; i++) {
                    if (!deg_in[i]) st.push_back(i);
                }
                for (int n = 0; n < _n; n++) {
                    if (int(st.size()) == n) return false; // Not DAG
                    int now = st[n];
                    for (int i = g.start[now]; i < g.start[now + 1]; i++) {
                        const auto &e = g.elist[i];
                        if (!e.cap) continue;
                        deg_in[e.to]--;
                        if (deg_in[e.to] == 0) st.push_back(e.to);
                        if (dual_dist[e.to].first >= dual_dist[now].first + e.cost)
                            dual_dist[e.to].first = dual_dist[now].first + e.cost;
                    }
                }
                return true;
            }();
            if (!check_dag) throw;
            auto dt = dual_dist[t].first;
            for (int v = 0; v < _n; v++) dual_dist[v].first -= dt;
            is_dual_infeasible = false;
        }
        std::vector<int> prev_e(_n);
        std::vector<bool> vis(_n);
        struct Q {
            Cost key;
            int to;
            bool operator<(Q r) const { return key > r.key; }
        };
        std::vector<int> que_min;
        std::vector<Q> que;
        auto dual_ref = [&]() {
            for (int i = 0; i < _n; i++) {
                dual_dist[i].second = std::numeric_limits<Cost>::max();
            }
            std::fill(vis.begin(), vis.end(), false);
            que_min.clear();
            que.clear();

            // que[0..heap_r) was heapified
            unsigned heap_r = 0;

            dual_dist[s].second = 0;
            que_min.push_back(s);
            while (!que_min.empty() || !que.empty()) {
                int v;
                if (!que_min.empty()) {
                    v = que_min.back();
                    que_min.pop_back();
                } else {
                    while (heap_r < que.size()) {
                        heap_r++;
                        std::push_heap(que.begin(), que.begin() + heap_r);
                    }
                    v = que.front().to;
                    std::pop_heap(que.begin(), que.end());
                    que.pop_back();
                    heap_r--;
                }
                if (vis[v]) continue;
                vis[v] = true;
                if (v == t) break;
                // dist[v] = shortest(s, v) + dual[s] - dual[v]
                // dist[v] >= 0 (all reduced cost are positive)
                // dist[v] <= (n-1)C
                Cost dual_v = dual_dist[v].first, dist_v = dual_dist[v].second;
                for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                    auto e = g.elist[i];
                    if (!e.cap) continue;
                    // |-dual[e.to] + dual[v]| <= (n-1)C
                    // cost <= C - -(n-1)C + 0 = nC
                    Cost cost = e.cost - dual_dist[e.to].first + dual_v;
                    if (dual_dist[e.to].second - dist_v > cost) {
                        Cost dist_to = dist_v + cost;
                        dual_dist[e.to].second = dist_to;
                        prev_e[e.to] = e.rev;
                        if (dist_to == dist_v) {
                            que_min.push_back(e.to);
                        } else {
                            que.push_back(Q{dist_to, e.to});
                        }
                    }
                }
            }
            if (!vis[t]) { return false; }

            for (int v = 0; v < _n; v++) {
                if (!vis[v]) continue;
                // dual[v] = dual[v] - dist[t] + dist[v]
                //         = dual[v] - (shortest(s, t) + dual[s] - dual[t]) +
                //         (shortest(s, v) + dual[s] - dual[v]) = - shortest(s,
                //         t) + dual[t] + shortest(s, v) = shortest(s, v) -
                //         shortest(s, t) >= 0 - (n-1)C
                dual_dist[v].first -= dual_dist[t].second - dual_dist[v].second;
            }
            return true;
        };
        Cap flow = 0;
        Cost cost = 0, prev_cost_per_flow = -1;
        std::vector<std::pair<Cap, Cost>> result = {{Cap(0), Cost(0)}};
        while (flow < flow_limit) {
            if (!dual_ref()) break;
            Cap c = flow_limit - flow;
            for (int v = t; v != s; v = g.elist[prev_e[v]].to) {
                c = std::min(c, g.elist[g.elist[prev_e[v]].rev].cap);
            }
            for (int v = t; v != s; v = g.elist[prev_e[v]].to) {
                auto &e = g.elist[prev_e[v]];
                e.cap += c;
                g.elist[e.rev].cap -= c;
            }
            Cost d = -dual_dist[s].first;
            flow += c;
            cost += c * d;
            if (prev_cost_per_flow == d) { result.pop_back(); }
            result.push_back({flow, cost});
            prev_cost_per_flow = d;
        }
        return result;
    }
};


int main() {

    auto sort_by_subtree_size = [&](const vector<vector<int>> &to, vector<pint> &st, bool add_all = false) {
        const int N = to.size();
        vector<tuple<int, int, int>> stuv;
        for (auto [root, par] : st) {
            int cnt = 0;
            auto rec = [&](auto &&self, int now, int prv) -> void {
                cnt++;
                for (auto nxt : to[now]) {
                    if (nxt == prv) continue;
                    self(self, nxt, now);
                }
            };
            rec(rec, root, par);
            stuv.emplace_back(cnt, root, par);
        }
        sort(stuv.begin(), stuv.end());
        st.clear();
        for (auto [s, u, v] : stuv) st.emplace_back(u, v);
        REP(i, N) {
            st.emplace_back(i, -1), stuv.emplace_back(N, i, -1);
            if (!add_all) break;
        }
        return stuv;
    };

    int K;
    cin >> K;
    vector<vector<int>> to1(K);
    vector<pint> st1;

    REP(i, K - 1) {
        int a, b;
        cin >> a >> b;
        --a, --b;
        REP(t, 2) {
            to1[a].push_back(b);
            st1.emplace_back(a, b);
            swap(a, b);
        }
    }
    auto size_uv_1 = sort_by_subtree_size(to1, st1, true);
    map<pint, int> finder1;
    REP(i, st1.size()) finder1[st1[i]] = i;

    int N;
    cin >> N;
    vector<vector<int>> to2(N);
    vector<pint> st2;
    REP(i, N - 1) {
        int a, b;
        cin >> a >> b;
        --a, --b;
        REP(t, 2) {
            to2[a].emplace_back(b);
            st2.emplace_back(a, b);
            swap(a, b);
        }
    }
    auto size_uv_2 = sort_by_subtree_size(to2, st2);
    map<pint, int> finder2;
    REP(i, st2.size()) finder2[st2[i]] = i;

    const int size_diff = N - K;

    vector dp(st2.size(), vector<int>(st1.size(), -1000000));

    int ans = 0;
    REP(t2, st2.size()) {
        auto [root2, par2] = st2[t2];

        vector<int> ind2;
        for (auto ch2 : to2[root2]) {
            if (ch2 == par2) continue;
            int nx2 = finder2.at(pint(ch2, root2));
            REP(j, dp[t2].size()) {
                chmax(dp[t2][j], dp[nx2][j] + 1);
            }
            ind2.push_back(nx2);
        }

        REP(t1, st1.size()) {
            const int sz1 = get<0>(size_uv_1[t1]), sz2 = get<0>(size_uv_2[t2]);
            if (sz1 > sz2) continue;
            if (sz1 + (N - sz2) < K) continue;

            const auto [root1, par1] = st1[t1];
            vector<int> ind1;
            for (auto ch1 : to1[root1]) {
                if (ch1 == par1) continue;
                int nx1 = finder1.at(make_pair(ch1, root1));
                ind1.push_back(nx1);
            }
            int L1 = ind1.size(), R2 = ind2.size();
            const int gs = L1 + R2, gt = gs + 1;
            MinCostFlow<int, int> graph(gt + 1);
            // graph.set_supply(gs, L1);
            // graph.set_supply(gt, -L1);
            // REP(i, L1) graph.add_edge(gs, i, 0, 1, 0);
            REP(i, L1) graph.add_edge(gs, i, 1, 0);
            // REP(i, R2) graph.add_edge(L1 + i, gt, 0, 1, 0);
            REP(i, R2) graph.add_edge(L1 + i, gt, 1, 0);
            REP(i, L1) REP(j, R2) {
                int k2 = ind2[j];
                int k1 = ind1[i];
                // if (dp[k2][k1] > 0) graph.add_edge(i, L1 + j, 0, 1, -dp[k2][k1]);
                if (dp[k2][k1] > 0) graph.add_edge(i, L1 + j, 1, -dp[k2][k1]);
            }
            auto ret = graph.flow(gs, gt);
            // auto ret = graph.solve<int>();
            // if (!graph.infeasible or L1 == 0) {
            //     chmax(dp[t2][t1], -ret + 1);
            //     if (sz1 == K) chmax(ans, -ret + 1);
            // }
            if (ret.first == L1) {
                chmax(dp[t2][t1], -ret.second + 1);
                if (sz1 == K) chmax(ans, -ret.second + 1);
            }
        }
    }
    cout << ans - 1 << '\n';
}
0