結果
問題 | No.1789 Tree Growing |
ユーザー | NyaanNyaan |
提出日時 | 2021-12-18 12:27:38 |
言語 | C++17 (gcc 12.3.0 + boost 1.83.0) |
結果 |
AC
|
実行時間 | 13 ms / 5,000 ms |
コード長 | 37,545 bytes |
コンパイル時間 | 4,159 ms |
コンパイル使用メモリ | 309,000 KB |
実行使用メモリ | 5,376 KB |
最終ジャッジ日時 | 2024-09-15 12:42:18 |
合計ジャッジ時間 | 6,712 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 2 ms
5,248 KB |
testcase_01 | AC | 2 ms
5,248 KB |
testcase_02 | AC | 3 ms
5,376 KB |
testcase_03 | AC | 2 ms
5,376 KB |
testcase_04 | AC | 2 ms
5,376 KB |
testcase_05 | AC | 2 ms
5,376 KB |
testcase_06 | AC | 3 ms
5,376 KB |
testcase_07 | AC | 2 ms
5,376 KB |
testcase_08 | AC | 2 ms
5,376 KB |
testcase_09 | AC | 2 ms
5,376 KB |
testcase_10 | AC | 2 ms
5,376 KB |
testcase_11 | AC | 2 ms
5,376 KB |
testcase_12 | AC | 2 ms
5,376 KB |
testcase_13 | AC | 2 ms
5,376 KB |
testcase_14 | AC | 2 ms
5,376 KB |
testcase_15 | AC | 3 ms
5,376 KB |
testcase_16 | AC | 2 ms
5,376 KB |
testcase_17 | AC | 4 ms
5,376 KB |
testcase_18 | AC | 3 ms
5,376 KB |
testcase_19 | AC | 3 ms
5,376 KB |
testcase_20 | AC | 3 ms
5,376 KB |
testcase_21 | AC | 7 ms
5,376 KB |
testcase_22 | AC | 6 ms
5,376 KB |
testcase_23 | AC | 6 ms
5,376 KB |
testcase_24 | AC | 5 ms
5,376 KB |
testcase_25 | AC | 8 ms
5,376 KB |
testcase_26 | AC | 8 ms
5,376 KB |
testcase_27 | AC | 7 ms
5,376 KB |
testcase_28 | AC | 8 ms
5,376 KB |
testcase_29 | AC | 7 ms
5,376 KB |
testcase_30 | AC | 9 ms
5,376 KB |
testcase_31 | AC | 8 ms
5,376 KB |
testcase_32 | AC | 8 ms
5,376 KB |
testcase_33 | AC | 7 ms
5,376 KB |
testcase_34 | AC | 8 ms
5,376 KB |
testcase_35 | AC | 9 ms
5,376 KB |
testcase_36 | AC | 9 ms
5,376 KB |
testcase_37 | AC | 9 ms
5,376 KB |
testcase_38 | AC | 7 ms
5,376 KB |
testcase_39 | AC | 8 ms
5,376 KB |
testcase_40 | AC | 8 ms
5,376 KB |
testcase_41 | AC | 7 ms
5,376 KB |
testcase_42 | AC | 9 ms
5,376 KB |
testcase_43 | AC | 9 ms
5,376 KB |
testcase_44 | AC | 8 ms
5,376 KB |
testcase_45 | AC | 9 ms
5,376 KB |
testcase_46 | AC | 9 ms
5,376 KB |
testcase_47 | AC | 8 ms
5,376 KB |
testcase_48 | AC | 9 ms
5,376 KB |
testcase_49 | AC | 9 ms
5,376 KB |
testcase_50 | AC | 8 ms
5,376 KB |
testcase_51 | AC | 8 ms
5,376 KB |
testcase_52 | AC | 8 ms
5,376 KB |
testcase_53 | AC | 8 ms
5,376 KB |
testcase_54 | AC | 10 ms
5,376 KB |
testcase_55 | AC | 13 ms
5,376 KB |
testcase_56 | AC | 9 ms
5,376 KB |
testcase_57 | AC | 10 ms
5,376 KB |
testcase_58 | AC | 9 ms
5,376 KB |
testcase_59 | AC | 8 ms
5,376 KB |
testcase_60 | AC | 5 ms
5,376 KB |
testcase_61 | AC | 5 ms
5,376 KB |
testcase_62 | AC | 5 ms
5,376 KB |
testcase_63 | AC | 4 ms
5,376 KB |
testcase_64 | AC | 5 ms
5,376 KB |
testcase_65 | AC | 4 ms
5,376 KB |
testcase_66 | AC | 5 ms
5,376 KB |
testcase_67 | AC | 5 ms
5,376 KB |
testcase_68 | AC | 4 ms
5,376 KB |
testcase_69 | AC | 5 ms
5,376 KB |
testcase_70 | AC | 4 ms
5,376 KB |
testcase_71 | AC | 4 ms
5,376 KB |
testcase_72 | AC | 4 ms
5,376 KB |
testcase_73 | AC | 4 ms
5,376 KB |
testcase_74 | AC | 7 ms
5,376 KB |
testcase_75 | AC | 1 ms
5,376 KB |
testcase_76 | AC | 2 ms
5,376 KB |
testcase_77 | AC | 6 ms
5,376 KB |
testcase_78 | AC | 6 ms
5,376 KB |
testcase_79 | AC | 3 ms
5,376 KB |
testcase_80 | AC | 9 ms
5,376 KB |
testcase_81 | AC | 9 ms
5,376 KB |
testcase_82 | AC | 10 ms
5,376 KB |
testcase_83 | AC | 10 ms
5,376 KB |
testcase_84 | AC | 10 ms
5,376 KB |
testcase_85 | AC | 10 ms
5,376 KB |
testcase_86 | AC | 10 ms
5,376 KB |
testcase_87 | AC | 11 ms
5,376 KB |
コンパイルメッセージ
main.cpp:805:7: warning: 'template<class _Category, class _Tp, class _Distance, class _Pointer, class _Reference> struct std::iterator' is deprecated [-Wdeprecated-declarations] In file included from /home/linuxbrew/.linuxbrew/Cellar/gcc@12/12.3.0/include/c++/12/bits/stl_algobase.h:65, from /home/linuxbrew/.linuxbrew/Cellar/gcc@12/12.3.0/include/c++/12/algorithm:60, from main.cpp:11: /home/linuxbrew/.linuxbrew/Cellar/gcc@12/12.3.0/include/c++/12/bits/stl_iterator_base_types.h:127:34: note: declared here 127 | struct _GLIBCXX17_DEPRECATED iterator | ^~~~~~~~ main.cpp:807:7: warning: 'template<class _Category, class _Tp, class _Distance, class _Pointer, class _Reference> struct std::iterator' is deprecated [-Wdeprecated-declarations] /home/linuxbrew/.linuxbrew/Cellar/gcc@12/12.3.0/include/c++/12/bits/stl_iterator_base_types.h:127:34: note: declared here 127 | struct _GLIBCXX17_DEPRECATED iterator | ^~~~~~~~
ソースコード
/** * date : 2021-12-18 12:27:34 */ #define NDEBUG using namespace std; // intrinstic #include <immintrin.h> #include <algorithm> #include <array> #include <bitset> #include <cassert> #include <cctype> #include <cfenv> #include <cfloat> #include <chrono> #include <cinttypes> #include <climits> #include <cmath> #include <complex> #include <cstdarg> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <fstream> #include <functional> #include <initializer_list> #include <iomanip> #include <ios> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <random> #include <set> #include <sstream> #include <stack> #include <streambuf> #include <string> #include <tuple> #include <type_traits> #include <typeinfo> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> // utility namespace Nyaan { using ll = long long; using i64 = long long; using u64 = unsigned long long; using i128 = __int128_t; using u128 = __uint128_t; template <typename T> using V = vector<T>; template <typename T> using VV = vector<vector<T>>; using vi = vector<int>; using vl = vector<long long>; using vd = V<double>; using vs = V<string>; using vvi = vector<vector<int>>; using vvl = vector<vector<long long>>; template <typename T, typename U> struct P : pair<T, U> { template <typename... Args> P(Args... args) : pair<T, U>(args...) {} using pair<T, U>::first; using pair<T, U>::second; T &x() { return first; } const T &x() const { return first; } U &y() { return second; } const U &y() const { return second; } P &operator+=(const P &r) { first += r.first; second += r.second; return *this; } P &operator-=(const P &r) { first -= r.first; second -= r.second; return *this; } P &operator*=(const P &r) { first *= r.first; second *= r.second; return *this; } P operator+(const P &r) const { return P(*this) += r; } P operator-(const P &r) const { return P(*this) -= r; } P operator*(const P &r) const { return P(*this) *= r; } P operator*(int r) const { return {first * r, second * r}; } P operator-() const { return P{-first, -second}; } }; using pl = P<ll, ll>; using pi = P<int, int>; using vp = V<pl>; constexpr int inf = 1001001001; constexpr long long infLL = 4004004004004004004LL; template <typename T> int sz(const T &t) { return t.size(); } template <typename T, typename U> inline bool amin(T &x, U y) { return (y < x) ? (x = y, true) : false; } template <typename T, typename U> inline bool amax(T &x, U y) { return (x < y) ? (x = y, true) : false; } template <typename T> inline T Max(const vector<T> &v) { return *max_element(begin(v), end(v)); } template <typename T> inline T Min(const vector<T> &v) { return *min_element(begin(v), end(v)); } template <typename T> inline long long Sum(const vector<T> &v) { return accumulate(begin(v), end(v), 0LL); } template <typename T> int lb(const vector<T> &v, const T &a) { return lower_bound(begin(v), end(v), a) - begin(v); } template <typename T> int ub(const vector<T> &v, const T &a) { return upper_bound(begin(v), end(v), a) - begin(v); } constexpr long long TEN(int n) { long long ret = 1, x = 10; for (; n; x *= x, n >>= 1) ret *= (n & 1 ? x : 1); return ret; } template <typename T, typename U> pair<T, U> mkp(const T &t, const U &u) { return make_pair(t, u); } template <typename T> vector<T> mkrui(const vector<T> &v, bool rev = false) { vector<T> ret(v.size() + 1); if (rev) { for (int i = int(v.size()) - 1; i >= 0; i--) ret[i] = v[i] + ret[i + 1]; } else { for (int i = 0; i < int(v.size()); i++) ret[i + 1] = ret[i] + v[i]; } return ret; }; template <typename T> vector<T> mkuni(const vector<T> &v) { vector<T> ret(v); sort(ret.begin(), ret.end()); ret.erase(unique(ret.begin(), ret.end()), ret.end()); return ret; } template <typename F> vector<int> mkord(int N, F f) { vector<int> ord(N); iota(begin(ord), end(ord), 0); sort(begin(ord), end(ord), f); return ord; } template <typename T> vector<int> mkinv(vector<T> &v) { int max_val = *max_element(begin(v), end(v)); vector<int> inv(max_val + 1, -1); for (int i = 0; i < (int)v.size(); i++) inv[v[i]] = i; return inv; } } // namespace Nyaan // bit operation namespace Nyaan { __attribute__((target("popcnt"))) inline int popcnt(const u64 &a) { return _mm_popcnt_u64(a); } inline int lsb(const u64 &a) { return a ? __builtin_ctzll(a) : 64; } inline int ctz(const u64 &a) { return a ? __builtin_ctzll(a) : 64; } inline int msb(const u64 &a) { return a ? 63 - __builtin_clzll(a) : -1; } template <typename T> inline int gbit(const T &a, int i) { return (a >> i) & 1; } template <typename T> inline void sbit(T &a, int i, bool b) { if (gbit(a, i) != b) a ^= T(1) << i; } constexpr long long PW(int n) { return 1LL << n; } constexpr long long MSK(int n) { return (1LL << n) - 1; } } // namespace Nyaan // inout namespace Nyaan { template <typename T, typename U> ostream &operator<<(ostream &os, const pair<T, U> &p) { os << p.first << " " << p.second; return os; } template <typename T, typename U> istream &operator>>(istream &is, pair<T, U> &p) { is >> p.first >> p.second; return is; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { int s = (int)v.size(); for (int i = 0; i < s; i++) os << (i ? " " : "") << v[i]; return os; } template <typename T> istream &operator>>(istream &is, vector<T> &v) { for (auto &x : v) is >> x; return is; } void in() {} template <typename T, class... U> void in(T &t, U &... u) { cin >> t; in(u...); } void out() { cout << "\n"; } template <typename T, class... U, char sep = ' '> void out(const T &t, const U &... u) { cout << t; if (sizeof...(u)) cout << sep; out(u...); } void outr() {} template <typename T, class... U, char sep = ' '> void outr(const T &t, const U &... u) { cout << t; outr(u...); } struct IoSetupNya { IoSetupNya() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); cerr << fixed << setprecision(7); } } iosetupnya; } // namespace Nyaan // debug namespace DebugImpl { template <typename U, typename = void> struct is_specialize : false_type {}; template <typename U> struct is_specialize< U, typename conditional<false, typename U::iterator, void>::type> : true_type {}; template <typename U> struct is_specialize< U, typename conditional<false, decltype(U::first), void>::type> : true_type {}; template <typename U> struct is_specialize<U, enable_if_t<is_integral<U>::value, void>> : true_type { }; void dump(const char& t) { cerr << t; } void dump(const string& t) { cerr << t; } void dump(const bool& t) { cerr << (t ? "true" : "false"); } template <typename U, enable_if_t<!is_specialize<U>::value, nullptr_t> = nullptr> void dump(const U& t) { cerr << t; } template <typename T> void dump(const T& t, enable_if_t<is_integral<T>::value>* = nullptr) { string res; if (t == Nyaan::inf) res = "inf"; if constexpr (is_signed<T>::value) { if (t == -Nyaan::inf) res = "-inf"; } if constexpr (sizeof(T) == 8) { if (t == Nyaan::infLL) res = "inf"; if constexpr (is_signed<T>::value) { if (t == -Nyaan::infLL) res = "-inf"; } } if (res.empty()) res = to_string(t); cerr << res; } template <typename T, typename U> void dump(const pair<T, U>&); template <typename T> void dump(const pair<T*, int>&); template <typename T> void dump(const T& t, enable_if_t<!is_void<typename T::iterator>::value>* = nullptr) { cerr << "[ "; for (auto it = t.begin(); it != t.end();) { dump(*it); cerr << (++it == t.end() ? "" : ", "); } cerr << " ]"; } template <typename T, typename U> void dump(const pair<T, U>& t) { cerr << "( "; dump(t.first); cerr << ", "; dump(t.second); cerr << " )"; } template <typename T> void dump(const pair<T*, int>& t) { cerr << "[ "; for (int i = 0; i < t.second; i++) { dump(t.first[i]); cerr << (i == t.second - 1 ? "" : ", "); } cerr << " ]"; } void trace() { cerr << endl; } template <typename Head, typename... Tail> void trace(Head&& head, Tail&&... tail) { cerr << " "; dump(head); if (sizeof...(tail) != 0) cerr << ","; trace(forward<Tail>(tail)...); } } // namespace DebugImpl #ifdef NyaanDebug #define trc(...) \ do { \ cerr << "## " << #__VA_ARGS__ << " = "; \ DebugImpl::trace(__VA_ARGS__); \ } while (0) #else #define trc(...) (void(0)) #endif // macro #define each(x, v) for (auto&& x : v) #define each2(x, y, v) for (auto&& [x, y] : v) #define all(v) (v).begin(), (v).end() #define rep(i, N) for (long long i = 0; i < (long long)(N); i++) #define repr(i, N) for (long long i = (long long)(N)-1; i >= 0; i--) #define rep1(i, N) for (long long i = 1; i <= (long long)(N); i++) #define repr1(i, N) for (long long i = (N); (long long)(i) > 0; i--) #define reg(i, a, b) for (long long i = (a); i < (b); i++) #define regr(i, a, b) for (long long i = (b)-1; i >= (a); i--) #define fi first #define se second #define ini(...) \ int __VA_ARGS__; \ in(__VA_ARGS__) #define inl(...) \ long long __VA_ARGS__; \ in(__VA_ARGS__) #define ins(...) \ string __VA_ARGS__; \ in(__VA_ARGS__) #define in2(s, t) \ for (int i = 0; i < (int)s.size(); i++) { \ in(s[i], t[i]); \ } #define in3(s, t, u) \ for (int i = 0; i < (int)s.size(); i++) { \ in(s[i], t[i], u[i]); \ } #define in4(s, t, u, v) \ for (int i = 0; i < (int)s.size(); i++) { \ in(s[i], t[i], u[i], v[i]); \ } #define die(...) \ do { \ Nyaan::out(__VA_ARGS__); \ return; \ } while (0) namespace Nyaan { void solve(); } int main() { Nyaan::solve(); } // namespace atcoder { namespace internal { template <class E> struct csr { std::vector<int> start; std::vector<E> elist; 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; } } }; } // namespace internal } // namespace atcoder namespace atcoder { namespace internal { template <class T> struct simple_queue { std::vector<T> payload; int pos = 0; void reserve(int n) { payload.reserve(n); } int size() const { return int(payload.size()) - pos; } bool empty() const { return pos == int(payload.size()); } void push(const T& t) { payload.push_back(t); } T& front() { return payload[pos]; } void clear() { payload.clear(); pos = 0; } void pop() { pos++; } }; } // namespace internal } // namespace atcoder namespace atcoder { template <class Cap, class Cost> struct mcf_graph { public: mcf_graph() {} mcf_graph(int n) : _n(n) {} int add_edge(int from, int to, Cap cap, Cost cost) { assert(0 <= from && from < _n); assert(0 <= to && to < _n); assert(0 <= cap); assert(0 <= cost); 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 = internal::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: int _n; std::vector<edge> _edges; // inside edge struct _edge { int to, rev; Cap cap; Cost cost; }; std::vector<std::pair<Cap, Cost>> slope(internal::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); 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 size_t 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; } }; } // namespace atcoder template <typename T> struct edge { int src, to; T cost; edge(int _to, T _cost) : src(-1), to(_to), cost(_cost) {} edge(int _src, int _to, T _cost) : src(_src), to(_to), cost(_cost) {} edge &operator=(const int &x) { to = x; return *this; } operator int() const { return to; } }; template <typename T> using Edges = vector<edge<T>>; template <typename T> using WeightedGraph = vector<Edges<T>>; using UnweightedGraph = vector<vector<int>>; // Input of (Unweighted) Graph UnweightedGraph graph(int N, int M = -1, bool is_directed = false, bool is_1origin = true) { UnweightedGraph g(N); if (M == -1) M = N - 1; for (int _ = 0; _ < M; _++) { int x, y; cin >> x >> y; if (is_1origin) x--, y--; g[x].push_back(y); if (!is_directed) g[y].push_back(x); } return g; } // Input of Weighted Graph template <typename T> WeightedGraph<T> wgraph(int N, int M = -1, bool is_directed = false, bool is_1origin = true) { WeightedGraph<T> g(N); if (M == -1) M = N - 1; for (int _ = 0; _ < M; _++) { int x, y; cin >> x >> y; T c; cin >> c; if (is_1origin) x--, y--; g[x].emplace_back(x, y, c); if (!is_directed) g[y].emplace_back(y, x, c); } return g; } // Input of Edges template <typename T> Edges<T> esgraph(int N, int M, int is_weighted = true, bool is_1origin = true) { Edges<T> es; for (int _ = 0; _ < M; _++) { int x, y; cin >> x >> y; T c; if (is_weighted) cin >> c; else c = 1; if (is_1origin) x--, y--; es.emplace_back(x, y, c); } return es; } // Input of Adjacency Matrix template <typename T> vector<vector<T>> adjgraph(int N, int M, T INF, int is_weighted = true, bool is_directed = false, bool is_1origin = true) { vector<vector<T>> d(N, vector<T>(N, INF)); for (int _ = 0; _ < M; _++) { int x, y; cin >> x >> y; T c; if (is_weighted) cin >> c; else c = 1; if (is_1origin) x--, y--; d[x][y] = c; if (!is_directed) d[y][x] = c; } return d; } /** * @brief グラフテンプレート * @docs docs/graph/graph-template.md */ namespace HashMapImpl { using u32 = uint32_t; using u64 = uint64_t; template <typename Key, typename Data> struct HashMapBase; template <typename Key, typename Data> struct itrB : iterator<bidirectional_iterator_tag, Data, ptrdiff_t, Data*, Data&> { using base = iterator<bidirectional_iterator_tag, Data, ptrdiff_t, Data*, Data&>; using ptr = typename base::pointer; using ref = typename base::reference; u32 i; HashMapBase<Key, Data>* p; explicit constexpr itrB() : i(0), p(nullptr) {} explicit constexpr itrB(u32 _i, HashMapBase<Key, Data>* _p) : i(_i), p(_p) {} explicit constexpr itrB(u32 _i, const HashMapBase<Key, Data>* _p) : i(_i), p(const_cast<HashMapBase<Key, Data>*>(_p)) {} friend void swap(itrB& l, itrB& r) { swap(l.i, r.i), swap(l.p, r.p); } friend bool operator==(const itrB& l, const itrB& r) { return l.i == r.i; } friend bool operator!=(const itrB& l, const itrB& r) { return l.i != r.i; } const ref operator*() const { return const_cast<const HashMapBase<Key, Data>*>(p)->data[i]; } ref operator*() { return p->data[i]; } ptr operator->() const { return &(p->data[i]); } itrB& operator++() { assert(i != p->cap && "itr::operator++()"); do { i++; if (i == p->cap) break; if (p->flag[i] == true && p->dflag[i] == false) break; } while (true); return (*this); } itrB operator++(int) { itrB it(*this); ++(*this); return it; } itrB& operator--() { do { i--; if (p->flag[i] == true && p->dflag[i] == false) break; assert(i != 0 && "itr::operator--()"); } while (true); return (*this); } itrB operator--(int) { itrB it(*this); --(*this); return it; } }; template <typename Key, typename Data> struct HashMapBase { using u32 = uint32_t; using u64 = uint64_t; using iterator = itrB<Key, Data>; using itr = iterator; protected: template <typename K> inline u64 randomized(const K& key) const { return u64(key) ^ r; } template <typename K, enable_if_t<is_same<K, Key>::value, nullptr_t> = nullptr, enable_if_t<is_integral<K>::value, nullptr_t> = nullptr> inline u32 inner_hash(const K& key) const { return (randomized(key) * 11995408973635179863ULL) >> shift; } template < typename K, enable_if_t<is_same<K, Key>::value, nullptr_t> = nullptr, enable_if_t<is_integral<decltype(K::first)>::value, nullptr_t> = nullptr, enable_if_t<is_integral<decltype(K::second)>::value, nullptr_t> = nullptr> inline u32 inner_hash(const K& key) const { u64 a = randomized(key.first), b = randomized(key.second); a *= 11995408973635179863ULL; b *= 10150724397891781847ULL; return (a + b) >> shift; } template <typename K, enable_if_t<is_same<K, Key>::value, nullptr_t> = nullptr, enable_if_t<is_integral<typename K::value_type>::value, nullptr_t> = nullptr> inline u32 inner_hash(const K& key) const { static constexpr u64 mod = (1LL << 61) - 1; static constexpr u64 base = 950699498548472943ULL; u64 res = 0; for (auto& elem : key) { __uint128_t x = __uint128_t(res) * base + (randomized(elem) & mod); res = (x & mod) + (x >> 61); } __uint128_t x = __uint128_t(res) * base; res = (x & mod) + (x >> 61); if (res >= mod) res -= mod; return res >> (shift - 3); } template <typename D = Data, enable_if_t<is_same<D, Key>::value, nullptr_t> = nullptr> inline u32 hash(const D& dat) const { return inner_hash(dat); } template < typename D = Data, enable_if_t<is_same<decltype(D::first), Key>::value, nullptr_t> = nullptr> inline u32 hash(const D& dat) const { return inner_hash(dat.first); } template <typename D = Data, enable_if_t<is_same<D, Key>::value, nullptr_t> = nullptr> inline Key dtok(const D& dat) const { return dat; } template < typename D = Data, enable_if_t<is_same<decltype(D::first), Key>::value, nullptr_t> = nullptr> inline Key dtok(const D& dat) const { return dat.first; } void reallocate(u32 ncap) { vector<Data> ndata(ncap); vector<bool> nf(ncap); shift = 64 - __lg(ncap); for (u32 i = 0; i < cap; i++) { if (flag[i] == true && dflag[i] == false) { u32 h = hash(data[i]); while (nf[h]) h = (h + 1) & (ncap - 1); ndata[h] = move(data[i]); nf[h] = true; } } data.swap(ndata); flag.swap(nf); cap = ncap; dflag.resize(cap); fill(std::begin(dflag), std::end(dflag), false); } inline bool extend_rate(u32 x) const { return x * 2 >= cap; } inline bool shrink_rate(u32 x) const { return HASHMAP_DEFAULT_SIZE < cap && x * 10 <= cap; } inline void extend() { reallocate(cap << 1); } inline void shrink() { reallocate(cap >> 1); } public: u32 cap, s; vector<Data> data; vector<bool> flag, dflag; u32 shift; static u64 r; static constexpr uint32_t HASHMAP_DEFAULT_SIZE = 4; explicit HashMapBase() : cap(HASHMAP_DEFAULT_SIZE), s(0), data(cap), flag(cap), dflag(cap), shift(64 - __lg(cap)) {} itr begin() const { u32 h = 0; while (h != cap) { if (flag[h] == true && dflag[h] == false) break; h++; } return itr(h, this); } itr end() const { return itr(this->cap, this); } friend itr begin(const HashMapBase& h) { return h.begin(); } friend itr end(const HashMapBase& h) { return h.end(); } itr find(const Key& key) const { u32 h = inner_hash(key); while (true) { if (flag[h] == false) return this->end(); if (dtok(data[h]) == key) { if (dflag[h] == true) return this->end(); return itr(h, this); } h = (h + 1) & (cap - 1); } } bool contain(const Key& key) const { return find(key) != this->end(); } itr insert(const Data& d) { u32 h = hash(d); while (true) { if (flag[h] == false) { if (extend_rate(s + 1)) { extend(); h = hash(d); continue; } data[h] = d; flag[h] = true; ++s; return itr(h, this); } if (dtok(data[h]) == dtok(d)) { if (dflag[h] == true) { data[h] = d; dflag[h] = false; ++s; } return itr(h, this); } h = (h + 1) & (cap - 1); } } // tips for speed up : // if return value is unnecessary, make argument_2 false. itr erase(itr it, bool get_next = true) { if (it == this->end()) return this->end(); s--; if (shrink_rate(s)) { Data d = data[it.i]; shrink(); it = find(dtok(d)); } int ni = (it.i + 1) & (cap - 1); if (this->flag[ni]) { this->dflag[it.i] = true; } else { this->flag[it.i] = false; } if (get_next) ++it; return it; } itr erase(const Key& key) { return erase(find(key)); } bool empty() const { return s == 0; } int size() const { return s; } void clear() { fill(std::begin(flag), std::end(flag), false); fill(std::begin(dflag), std::end(dflag), false); s = 0; } void reserve(int n) { if (n <= 0) return; n = 1 << min(23, __lg(n) + 2); if (cap < u32(n)) reallocate(n); } }; template <typename Key, typename Data> uint64_t HashMapBase<Key, Data>::r = chrono::duration_cast<chrono::nanoseconds>( chrono::high_resolution_clock::now().time_since_epoch()) .count(); } // namespace HashMapImpl /** * @brief Hash Map(base) (ハッシュマップ・基底クラス) */ template <typename Key, typename Val> struct HashMap : HashMapImpl::HashMapBase<Key, pair<Key, Val>> { using base = typename HashMapImpl::HashMapBase<Key, pair<Key, Val>>; using HashMapImpl::HashMapBase<Key, pair<Key, Val>>::HashMapBase; using Data = pair<Key, Val>; Val& operator[](const Key& k) { typename base::u32 h = base::inner_hash(k); while (true) { if (base::flag[h] == false) { if (base::extend_rate(base::s + 1)) { base::extend(); h = base::hash(k); continue; } base::data[h].first = k; base::data[h].second = Val(); base::flag[h] = true; ++base::s; return base::data[h].second; } if (base::data[h].first == k) { if (base::dflag[h] == true) base::data[h].second = Val(); return base::data[h].second; } h = (h + 1) & (base::cap - 1); } } typename base::itr emplace(const Key& key, const Val& val) { return base::insert(Data(key, val)); } }; /* * @brief ハッシュマップ(連想配列) * @docs docs/hashmap/hashmap.md **/ namespace inner { using u64 = unsigned long long; using u128 = __uint128_t; template <int BASE_NUM = 2> struct Hash : array<u64, BASE_NUM> { using array<u64, BASE_NUM>::operator[]; static constexpr int n = BASE_NUM; Hash() : array<u64, BASE_NUM>() {} static constexpr u64 md = (1ull << 61) - 1; constexpr static Hash set(const long long &a) { Hash res; for (int i = 0; i < n; i++) res[i] = cast(a); return res; } Hash &operator+=(const Hash &r) { for (int i = 0; i < n; i++) if (((*this)[i] += r[i]) >= md) (*this)[i] -= md; return *this; } Hash &operator+=(const u64 &r) { for (int i = 0; i < n; i++) if (((*this)[i] += r) >= md) (*this)[i] -= md; return *this; } Hash &operator-=(const Hash &r) { for (int i = 0; i < n; i++) if (((*this)[i] += md - r[i]) >= md) (*this)[i] -= md; return *this; } Hash &operator-=(const u64 &r) { for (int i = 0; i < n; i++) if (((*this)[i] += md - r) >= md) (*this)[i] -= md; return *this; } inline Hash &operator*=(const Hash &r) { for (int i = 0; i < n; i++) (*this)[i] = modmul((*this)[i], r[i]); return *this; } Hash operator+(const Hash &r) { return Hash(*this) += r; } Hash operator+(const u64 &r) { return Hash(*this) += r; } Hash operator-(const Hash &r) { return Hash(*this) -= r; } Hash operator-(const u64 &r) { return Hash(*this) -= r; } inline Hash operator*(const Hash &r) { return Hash(*this) *= r; } Hash operator-() const { Hash res; for (int i = 0; i < n; i++) res[i] = (*this)[i] == 0 ? 0 : md - (*this)[i]; return res; } friend Hash pfma(const Hash &a, const Hash &b, const Hash &c) { Hash res; for (int i = 0; i < n; i++) res[i] = modfma(a[i], b[i], c[i]); return res; } friend Hash pfma(const Hash &a, const Hash &b, const long long &c) { Hash res; for (int i = 0; i < n; i++) res[i] = modfma(a[i], b[i], cast(c)); return res; } static Hash get_basis() { static auto rand_time = chrono::duration_cast<chrono::nanoseconds>( chrono::high_resolution_clock::now().time_since_epoch()) .count(); static mt19937_64 rng(rand_time); Hash h; for (int i = 0; i < n; i++) { while (isPrimitive(h[i] = rng() % (md - 1) + 1) == false) ; } return h; } private: static u64 modpow(u64 a, u64 b) { u64 r = 1; for (a %= md; b; a = modmul(a, a), b >>= 1) r = modmul(r, a); return r; } static bool isPrimitive(u64 x) { for (auto &d : vector<u64>{2, 3, 5, 7, 11, 13, 31, 41, 61, 151, 331, 1321}) if (modpow(x, (md - 1) / d) <= 1) return false; return true; } static inline constexpr u64 cast(const long long &a) { return a < 0 ? a + md : a; } static inline constexpr u64 modmul(const u64 &a, const u64 &b) { u128 ret = u128(a) * b; ret = (ret & md) + (ret >> 61); return ret >= md ? ret - md : ret; } static inline constexpr u64 modfma(const u64 &a, const u64 &b, const u64 &c) { u128 ret = u128(a) * b + c; ret = (ret & md) + (ret >> 61); return ret >= md ? ret - md : ret; } }; } // namespace inner /** * @brief ハッシュ構造体 * @docs docs/inner/inner-hash.md */ template <typename T> struct has_cost { private: template <typename U> static auto confirm(U u) -> decltype(u.cost, std::true_type()); static auto confirm(...) -> std::false_type; public: enum : bool { value = decltype(confirm(std::declval<T>()))::value }; }; template <typename T> vector<vector<T>> inverse_tree(const vector<vector<T>>& g) { int N = (int)g.size(); vector<vector<T>> rg(N); for (int i = 0; i < N; i++) { for (auto& e : g[i]) { if constexpr (is_same<T, int>::value) { rg[e].push_back(i); } else if constexpr (has_cost<T>::value) { rg[e].emplace_back(e.to, i, e.cost); } else { assert(0); } } } return rg; } template <typename T> vector<vector<T>> rooted_tree(const vector<vector<T>>& g, int root = 0) { int N = (int)g.size(); vector<vector<T>> rg(N); vector<char> v(N, false); v[root] = true; queue<int> que; que.emplace(root); while (!que.empty()) { auto p = que.front(); que.pop(); for (auto& e : g[p]) { if (v[e] == false) { v[e] = true; que.push(e); rg[p].push_back(e); } } } return rg; } /** * @brief 根付き木・逆辺からなる木への変換 */ template <typename G> struct TreeHash { using u64 = unsigned long long; using Hash = inner::Hash<1>; const G& g; int n; vector<Hash> hash; vector<int> depth; static vector<Hash>& xs() { static vector<Hash> _xs; return _xs; } TreeHash(const G& _g, int root = 0) : g(_g), n(g.size()) { hash.resize(n); depth.resize(n, 0); while ((int)xs().size() <= n) xs().push_back(Hash::get_basis()); dfs(root, -1); } private: int dfs(int c, int p) { int dep = 0; for (auto& d : g[c]) { if (d != p) dep = max(dep, dfs(d, c) + 1); } Hash x = xs()[dep], h = Hash::set(1); for (auto& d : g[c]) { if (d != p) h = h * (x + hash[d]); } hash[c] = h; return depth[c] = dep; } }; /* template <typename G> vector<typename TreeHash<G>::Hash> TreeHash<G>::xs; */ using namespace Nyaan; using Hash = typename TreeHash<vvi>::Hash; vi sub(vvi g, int r) { int N = sz(g); vi res(N, -1); auto dfs = [&](auto rc, int c, int p = -1, [[maybe_unused]] ll dat = 0) -> void { res[c] = 1; for (auto& d : g[c]) { if (d == p) continue; rc(rc, d, c); res[c] += res[d]; } }; dfs(dfs, r); return res; } HashMap<pair<u64, u64>, int> memo; int sol(int, vvi g, int, vvi h, int hr) { g = rooted_tree(g, 0); h = rooted_tree(h, hr); TreeHash hag(g, 0); TreeHash hah(h, hr); vi subg = sub(g, 0); vi subh = sub(h, hr); auto calc = [&](auto rc, int cg, int ch, bool ke = false) -> ll { pair<u64, u64> pa; if (!ke) { if (subg[cg] > subh[ch]) return inf; if (sz(g[cg]) > sz(h[ch])) return inf; pa = make_pair(hag.hash[cg][0], hah.hash[ch][0]); } else { if (subg[cg] + 1 > subh[ch]) return inf; auto h2 = hag.hash[cg] + hag.xs()[hag.depth[cg] + 1]; pa = make_pair(h2[0], hah.hash[ch][0]); } if (memo.find(pa) != end(memo)) return memo[pa]; using HS = pair<Hash, int>; map<HS, pl> mpg, mph; int kog = 0, koh = 0; if (ke) { mpg[{hag.hash[cg], subg[cg]}] = {1, cg}; kog = 1; } else { each(d, g[cg]) { auto& p = mpg[{hag.hash[d], subg[d]}]; p.first++; p.second = d; kog++; } } each(d, h[ch]) { auto& p = mph[{hah.hash[d], subh[d]}]; p.first++; p.second = d; koh++; } V<pair<HS, pl>> mpg2, mph2; each(p, mpg) mpg2.push_back(p); each(p, mph) mph2.push_back(p); atcoder::mcf_graph<ll, ll> mcf(sz(mpg) + 1 + sz(mph) + 2); int sg = sz(mpg2) + 1; int sh = sz(mph2); int S = sg + sh + 0; int T = sg + sh + 1; rep(i, sg - 1) mcf.add_edge(S, i + 0u, mpg2[i].second.first, 0); rep(i, sh + 0) mcf.add_edge(i + sg, T, mph2[i].second.first, 0); mcf.add_edge(S, sg - 1, koh - kog, 0); rep(i, sg) rep(j, sh) { int cost = inf; if (i == sz(mpg2)) { cost = mph2[j].first.second; } else { int daig = mpg2[i].second.second; int daih = mph2[j].second.second; cost = rc(rc, daig, daih); amin(cost, rc(rc, daig, daih, true)); } mcf.add_edge(i, sg + j, inf, cost); } auto [fl, ans] = mcf.flow(S, T); // each(e, mcf.edges()) trc(e.from, e.to, e.cap, e.cost, e.flow); if (ans > inf) ans = inf; trc(cg, ch, ke, fl, ans); trc(mpg); trc(mph); return memo[pa] = ans; }; return calc(calc, 0, hr); } void Nyaan::solve() { inl(K); auto g = graph(K); inl(N); auto h = graph(N); ll ans = inf; rep(i, N) { // if (i != 0) continue; // if (i != 1) continue; int cur = sol(K, g, N, h, i); trc(i, cur); amin(ans, cur); } if (ans == inf) ans = -1; else ans = N - 1 - ans; out(ans); }