Created
March 20, 2024 01:13
-
-
Save estelabn/8eaf6b8bab84af5a9d5237639023e0ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
typedef long long ll; | |
const int maxn = 1e5 + 5; | |
vector<pair<int,int>> adj[maxn]; | |
ll soma[maxn]; | |
vector<int> res; | |
void dfs(int x, int ant){ | |
for(auto [a,b]: adj[x]){ | |
if(a == ant) continue; | |
dfs(a,x); | |
soma[x] += soma[a]; | |
if(soma[a] == 0) res.push_back(b); | |
} | |
} | |
int main(){ | |
int n,k; cin >> n >> k; | |
for(int i=1; i<=n; i++) cin >> soma[i]; | |
for(int i=1; i<n; i++){ | |
int u,v,c; cin >> u >> v >> c; | |
adj[u].push_back({v,c}); | |
adj[v].push_back({u,c}); | |
} | |
dfs(1,0); | |
if(soma[1] != 0 or res.size() < k) cout << -1 << endl; | |
else{ | |
sort(res.begin(), res.end()); | |
ll tot = 0; | |
for(int i=0; i<k; i++) tot += res[i]; | |
cout << tot << endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment