Pagini recente » Cod sursa (job #3037512) | Cod sursa (job #286144) | Cod sursa (job #827573) | Cod sursa (job #812753) | Cod sursa (job #2812352)
#include <stdio.h>
#include <deque>
#include <vector>
using namespace std;
const int NMAX = 16000, INF = 1e7;
vector<int> edges[NMAX];
int smax[NMAX], leaves[NMAX], val[NMAX], father[NMAX], lvpt;
bool vis[NMAX];
deque<int> dq;
void getLeaves(int node);
void bfs(int leaves[], int &maxcur);
int main()
{
int n, i, v1, v2, root, maxx;
FILE *fin = fopen("asmax.in", "r");
fscanf(fin, "%d", &n);
for (i = 0; i < n; i++)
fscanf(fin, "%d", &val[i]);
for (i = 0; i < n - 1; i++)
{
fscanf(fin, "%d%d", &v1, &v2);
v1--, v2--;
edges[v1].push_back(v2);
edges[v2].push_back(v1);
}
fclose(fin);
root = 0;
father[root] = root;
getLeaves(root);
maxx = -INF;
bfs(leaves, maxx);
FILE *fout = fopen("asmax.out", "w");
fprintf(fout, "%d", maxx);
fclose(fout);
return 0;
}
void getLeaves(int node)
{
int i, len = edges[node].size(), nextnode;
if (len == 1 && father[node] != node)
{
leaves[lvpt++] = node;
return;
}
for (i = 0; i < len; i++)
{
nextnode = edges[node][i];
if (father[node] != nextnode)
{
father[nextnode] = node;
getLeaves(nextnode);
}
}
}
void bfs(int leaves[], int &maxcur)
{
int i, node, nextnode, len;
for (i = 0; i < lvpt; i++)
dq.push_front(leaves[i]);
while (!dq.empty())
{
node = dq.back();
dq.pop_back();
vis[node] = 1;
len = edges[node].size();
smax[node] = val[node];
for (i = 0; i < len; i++)
{
nextnode = edges[node][i];
if (nextnode != father[node])
smax[node] += max(smax[nextnode], 0);
}
if (smax[node] > maxcur)
maxcur = smax[node];
if (!vis[father[node]])
dq.push_front(father[node]);
}
}