이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
auto&operator<<(auto &o, pair<auto, auto> p) {o << "(" << p.first << ", " << p.second << ")"; return o;}
auto operator<<(auto &o, auto x)->decltype(x.end(), o) {o<<"{"; for(auto e : x) o<<e<<", "; return o<<"}";}
#define debug(X) cerr << "["#X"]: " << X << '\n';
#else
#define debug(X) ;
#endif
#define ll long long
#define all(v) (v).begin(), (v).end()
#define FOR(i,l,r) for(int i=(l);i<=(r);++i)
#define ROF(i,r,l) for(int i=(r);i>=(l);--i)
#define REP(i,n) FOR(i,0,(n)-1)
#define ssize(x) int(x.size())
#define fi first
#define se second
#define mp make_pair
#define eb emplace_back
int best_path(int n, int k, int h[][2], int l[]) {
vector<vector<pair<int, int>>> G(n);
REP(i, n-1) {
G[h[i][0]].eb(mp(h[i][1], l[i]));
G[h[i][1]].eb(mp(h[i][0], l[i]));
}
const int inf = 1e9;
int res = inf;
auto merge = [&](pair<pair<int, int>, map<int, int>> a, pair<pair<int, int>, map<int, int>> b) {
if (ssize(a.se) < ssize(b.se)) swap(a, b);
for (auto x : b.se) {
int key = x.fi+b.fi.fi;
if(a.se.find((k-key)-a.fi.fi) != a.se.end()) res = min(res, a.se[(k-key)-a.fi.fi]+a.fi.se+x.se+b.fi.se);
}
for (auto x : b.se) {
int key = x.fi+b.fi.fi;
if (a.se.find(key-a.fi.fi) == a.se.end()) a.se[key-a.fi.fi] = inf;
a.se[key-a.fi.fi] = min(a.se[key-a.fi.fi], x.se+b.fi.se-a.fi.se);
}
return a;
};
function<pair<pair<int, int>, map<int, int>>(int, int)> dfs = [&](int v, int p) {
pair<pair<int, int>, map<int, int>> A;
A.fi.fi = A.fi.se = 0;
A.se[0] = 0;
for (auto e : G[v]) {
int u = e.fi, w = e.se;
if (u == p) continue;
pair<pair<int, int>, map<int, int>> B = dfs(u, v);
B.fi.fi += w;
B.fi.se++;
A = merge(A, B);
}
return A;
};
dfs(0, -1);
if (res == inf) return -1;
return res;
}
#ifdef LOCAL
int main () {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k;
cin >> n >> k;
int h[n-1][2];
int l[n-1];
REP(i, n-1) {
cin >> h[i][0] >> h[i][1];
}
REP(i, n-1) {
cin >> l[i];
}
cout << best_path(n, k, h, l) << '\n';
return 0;
}
#endif
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |