From 5d740ba0ec2c44950bddbca3cefb83c5daa7687d Mon Sep 17 00:00:00 2001 From: DominicS99 <98355617+DominicS99@users.noreply.github.com> Date: Fri, 21 Apr 2023 15:43:46 -0700 Subject: [PATCH] Create dominic.cpp --- .../dominic.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Week 6/Extra Practice Problems (Week 6)/2646: Minimize the Total Price of the Trips/dominic.cpp diff --git a/Week 6/Extra Practice Problems (Week 6)/2646: Minimize the Total Price of the Trips/dominic.cpp b/Week 6/Extra Practice Problems (Week 6)/2646: Minimize the Total Price of the Trips/dominic.cpp new file mode 100644 index 0000000..6f0022a --- /dev/null +++ b/Week 6/Extra Practice Problems (Week 6)/2646: Minimize the Total Price of the Trips/dominic.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + int minimumTotalPrice(int n, vector>& edges, vector& price, vector>& trips) { + vector> al(n); + vector counts(n, 0); + for (auto &it : edges) { + al[it[0]].push_back(it[1]); + al[it[1]].push_back(it[0]); + } + + vector vis; + function dfs = [&] (int x, int end) { + if (x == end) return true; + vis[x] = 1; + + for (auto y : al[x]) { + if (x == y) continue; + if (vis[y]) continue; + + if(dfs(y, end)) { + counts[y]++; + return true; + } + } + return false; + }; + + for (auto &it : trips) { + vis.assign(n, 0); + dfs(it[0], it[1]); + counts[it[0]]++; + } + + vector> memo(n, vector(2, 1e9)); + + function addCounts = [&] (int x, bool f) { + int &curr = memo[x][f]; + if (curr != 1e9) return curr; + + if (f) curr = (counts[x]) * (price[x]/2); + else curr = counts[x] * price[x]; + + for (auto y : al[x]) { + if (x == y) continue; + if (vis[y]) continue; + + vis[y] = 1; + if (f) { + curr += addCounts(y, !f); + } else { + curr += min(addCounts(y, true), addCounts(y, false)); + } + vis[y] = 0; + } + + return curr; + }; + + vis.assign(n, 0); + vis[0] = 1; + int res = min(addCounts(0, true), addCounts(0, false)); + + return res; + } +};