公式
D - 接続規格と変換器 / Connection Standards and Converters 解説
by
D - 接続規格と変換器 / Connection Standards and Converters 解説
by
MMNMM
装置 \(1\) 以外のすべての装置それぞれの規格を選ぶ \(2 ^ {N-1}\) 通りの方法について、装置 \(1\) と関係しない部分の費用の合計を求められているとします。
このとき、答えを求めるためには、装置 \(1\) と直接ケーブルでつながれている装置 \(i\) について、以下のような値がわかっていれば十分です。
- 装置 \(1\) と装置 \(i\) を結ぶケーブルを取り除いて得られる \(2\) つの連結成分のうち装置 \(i\) が含まれているほうについて、装置 \(i\) の規格が規格 \(0\) であるときの連結成分内の費用の合計の最小値と、装置 \(i\) の規格が規格 \(1\) であるときの連結成分内の費用の合計の最小値
これらの値がわかれば、装置 \(1\) の規格を \(2\) 通り試し、直接ケーブルでつながれている装置それぞれについて費用の合計が大きくならないほうを選ぶことで答えを求めることができます。
よって、与えられるグラフを装置 \(1\) を根とした根つき木だと思うことで、次のような木 DP を考えることができます。
\(\operatorname{dp}[i][j]\coloneqq\) 装置 \(i\) を根とする部分木に含まれる装置の規格の選び方のうち、装置 \(i\) の規格が規格 \(j\) であるものの費用の合計の最小値 \((1\le i\le N,j=0,1)\)
求めるものは \(\min\lbrace\operatorname{dp}[1][0],\operatorname{dp}[1][1]\rbrace\) です。
この木 DP は DFS などを使うことで葉から値を計算することができ、十分高速にこの問題を解くことができます。
実装例は以下のようになります。
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;
int main() {
int N;
cin >> N;
vector<array<long, 2>> vertex_cost(N);
for (auto& [A, B] : vertex_cost) {
cin >> A >> B;
}
vector<vector<pair<int, int>>> edges(N);
for (int i = 1; i < N; ++i) {
int U, V, C;
cin >> U >> V >> C;
--U;
--V; // 0-indexed にしておく
edges[U].emplace_back(V, C);
edges[V].emplace_back(U, C);
}
cout << ranges::min([&vertex_cost, &edges](this auto dfs, int now, int prev) -> array<long, 2> {
// {装置 now の規格を 0 にするときの費用の最小値, 装置 now の規格を 1 にするときの費用の最小値} を求める
// 根にかかるコスト
array<long, 2> ret = vertex_cost[now];
// 子の結果を足す
for (auto [next, cost] : edges[now]) {
if (next != prev) {
array<long, 2> child_cost = dfs(next, now);
ret[0] += min(child_cost[0], child_cost[1] + cost);
ret[1] += min(child_cost[0] + cost, child_cost[1]);
}
}
return ret;
}(0, 0)) << endl;
return 0;
}
from sys import setrecursionlimit
setrecursionlimit(200000)
N = int(input())
vertex_cost = [list(map(int, input().split())) for i in range(N)]
edges = [[] for i in range(N)]
for i in range(N - 1):
U, V, C = map(int, input().split())
U -= 1
V -= 1 # 0-indexed にしておく
edges[U].append((V, C))
edges[V].append((U, C))
def dfs(now, prev):
# {装置 now の規格を 0 にするときの費用の最小値, 装置 now の規格を 1 にするときの費用の最小値} を求める
# 根にかかるコスト
ret = vertex_cost[now]
# 子の結果を足す
for next, cost in edges[now]:
if next != prev:
child_cost = dfs(next, now)
ret[0] += min(child_cost[0], child_cost[1] + cost)
ret[1] += min(child_cost[0] + cost, child_cost[1])
return ret
print(min(dfs(0, 0)))
