Pagini recente » Cod sursa (job #613829) | Cod sursa (job #3248895) | Cod sursa (job #1978842) | Cod sursa (job #2185104) | Cod sursa (job #997529)
Cod sursa(job #997529)
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
using namespace std;
class node {
public:
node() {};
~node() {};
long v;//node value
int i;//node index (in [1..N) )
list<node*> c;
};
#define max(x,y) (((x)>(y))?(x):(y))
class sol {
ifstream I;
ofstream O;
public:
int N;
vector<int> V;
vector<node*> nodes;
vector<int> sums;
vector<int> visited;
/* make that node the root of the tree */
void rootify(node* x) {
//for(x;
};
void read_data() {
int i,j;
I >> N;
nodes.push_back(new node()); // padding, we won't use this node ever
sums.push_back(0);
visited.push_back(0);
/* push node objects on the nodes vector */
for(i=0;i<N;i++)
nodes.push_back(new node()) ,
sums.push_back(0) ,
visited.push_back(0);
/* ->i is the label, and ->v is the value of that node */
for(i=0;i<N;i++){
int val;
I >> val;
nodes[i+1]->v = val;
nodes[i+1]->i = i+1;
};
/* get the edges and tie the nodes together to form the tree*/
for(i=0;i<N-1;i++) {
int n1,n2;
I >> n1 >> n2;
//cout << n1 << " " << n2 <<endl;
(nodes[n1]->c).push_front(nodes[n2]);
(nodes[n2]->c).push_front(nodes[n1]);
};
};
void solve() {
long smax = dfs(nodes[1]);
long m = -10000;
for(int i=1;i<N+1;i++) {
m = max(m,sums[i]);
};
//cout <<"smax="<<m<<endl;
O << m;
};
long dfs(node* r) {
//cout << "v="<< r->v << endl;
sums[r->i] = r->v;
visited[r->i] = 1;
for(list<node*>::iterator child = (r->c).begin(); child != (r->c).end(); child++){
if(visited[(*child)->i])
continue;
visited[(*child)->i] = 1;
long s = dfs(*child);
/* if maximum sum of subtree brings an improvement to
* the current sum, then update */
if(s + sums[r->i] > sums[r->i]) {
sums[r->i] += s;
};
};
return sums[r->i];
};
sol() : I("asmax.in"), O("asmax.out") {
};
~sol() {};
};
int main() {
sol s;
s.read_data();
s.solve();
return 0;
};