Pagini recente » Cod sursa (job #314608) | Cod sursa (job #1841538) | Cod sursa (job #944565) | Cod sursa (job #3149800) | Cod sursa (job #2651711)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("asmax.in");
ofstream fout("asmax.out");
#define d liste[top][i]
struct nod
{
int el, val, nivel;
};
int n;
long long int m;
vector<vector<int>> liste(16001, vector<int>());
vector<nod> noduri(16001);
vector<long long int> s(16001, 0);
queue<int> c;
int partition(vector<nod>& arr, int low, int high)
{
nod pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
if (arr[j].nivel > pivot.nivel)
{
i++; // increment index of smaller element
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quickSort(vector<nod>& arr, int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void bfs(vector<int> ocupat)
{
ocupat[1] = 1;
noduri[1].nivel = 0;
c.push(1);
while (!c.empty())
{
int top = c.front();
for (int i = 0; i < liste[top].size(); i++)
if (ocupat[d] == 0)
{
ocupat[d] = 1;
noduri[d].nivel = noduri[top].nivel + 1;
c.push(d);
}
c.pop();
}
}
int main()
{
fin >> n;
vector<int> ocupat(n + 1, 0);
vector<nod> sortate(n + 1);
int x = -1;
for (int i = 1; i <= n; i++)
{
fin >> noduri[i].val;
x = max(x, noduri[i].val);
}
if (x < 1)
{
fout << x;
return 0;
}
for (int i = 0; i < n - 1; i++)
{
int a, b;
fin >> a >> b;
liste[a].push_back(b);
liste[b].push_back(a);
}
bfs(ocupat);
for (int i = 1; i <= n; i++)
{
sortate[i] = noduri[i];
sortate[i].el = i;
}
quickSort(sortate, 1, n);
int nM = sortate[1].nivel;
for (int i = 1; i <= n; i++)
{
int el = sortate[i].el, nivel = sortate[i].nivel, val = sortate[i].val;
if (liste[el].size() == 1 && nivel != 0)
{
if (val > 0)
s[el] = val;
continue;
}
s[el] += val;
for (int j = 0; j < liste[el].size(); j++)
{
int dest = liste[el][j];
if (noduri[dest].nivel > nivel)
s[el] += s[dest];
}
m = max(m, s[el]);
}
fout << m;
}