Pagini recente » Cod sursa (job #275895) | Cod sursa (job #900965) | Cod sursa (job #1944540) | Cod sursa (job #2290845) | Cod sursa (job #2827239)
//
// main.cpp
// Asmax
//
// Created by Mara Dascalu on 05/01/2022.
//
#include <iostream>
#include <fstream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
ifstream input("asmax.in");
ofstream output("asmax.out");
vector<vector<int>> adj_list;
vector<int> cost;
vector<bool> visited;
int max_sum = INT_MIN;
int dfs(int node);
int main(int argc, const char * argv[])
{
int nodes;
input >> nodes;
cost.resize(nodes + 1);
for (int i = 1 ; i <= nodes ; i++)
input >> cost[i];
adj_list.resize(nodes + 1);
for (int i = 0; i < nodes - 1; i++) {
int x, y;
input >> x >> y;
adj_list[x].push_back(y);
adj_list[y].push_back(x);
}
visited.assign(nodes + 1, false);
dfs(1); //we cann start from any node, because they are all connected
output << max_sum;
}
int dfs(int node)
{
int sum = cost[node]; //for each node, we consider that it's maximum sum is it's cost
visited[node] = true;
for (int i = 0 ; i < adj_list[node].size() ; i++) //for each adjacent vertex with node
{
int adj_node = adj_list[node][i];
if (!visited[adj_node])
{
int new_sum = dfs(adj_node); //we calculate recursively the maximum sum we can obtain from the subtree that has that node as a root
if (sum + new_sum > sum) //check if the initial sum of the node increases if we add the sum of the subtree
sum += new_sum;
}
}
if (sum > max_sum)
max_sum = sum;
return sum;;
}