Created
May 20, 2020 02:37
-
-
Save Thiago4532/9d5ff2c434f03b93a0b6db0982e42e8b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 pair<int, int> pii; | |
| const int maxn = 1e5 + 10; | |
| int n, k, custo[maxn]; | |
| vector<pii> grafo[maxn]; | |
| vector<int> arestas; // Arestas que podem ser removidas | |
| int soma[maxn]; // Soma das componentes | |
| void dfs(int u, int p) { | |
| soma[u] = custo[u]; | |
| for (int i = 0; i < (int)grafo[u].size(); i++) { | |
| int v = grafo[u][i].first, peso = grafo[u][i].second; | |
| if (v == p) // Se o vizinho for o pai, ignorar ele. | |
| continue; | |
| dfs(v, u); | |
| if (soma[v] == 0) // Se a soma da componente for 0, podemos remover essa aresta. | |
| arestas.push_back(peso); // Guardaremos no vetor de arestas removiveis. | |
| soma[u] += soma[v]; | |
| } | |
| } | |
| int main() { | |
| cin >> n >> k; | |
| int soma_custo = 0; | |
| for (int i = 1; i <= n; i++) | |
| cin >> custo[i], soma_custo += custo[i]; | |
| if (soma_custo != 0) { | |
| cout << "-1\n"; | |
| return 0; | |
| } | |
| for (int i = 1; i < n; i++) { | |
| int a, b, c; | |
| cin >> a >> b >> c; | |
| grafo[a].push_back({b, c}); | |
| grafo[b].push_back({a, c}); | |
| } | |
| dfs(1, 0); | |
| sort(arestas.begin(), arestas.end()); // Ordenando as arestas removiveis e pegando as k primeiras. | |
| if ( arestas.size() < k ) { | |
| cout << "-1\n"; | |
| return 0; | |
| } | |
| int ans = 0; | |
| for (int i = 0; i < k; i++) | |
| ans += arestas[i]; | |
| cout << ans << "\n"; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment