Cod sursa(job #997520)

Utilizator stefan.petreaStefan Petrea stefan.petrea Data 14 septembrie 2013 13:23:31
Problema Asmax Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.44 kb
#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;

        /* 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);

            /* push node objects on the nodes vector */
            for(i=0;i<N;i++)
                nodes.push_back(new node()) ,
                sums.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;
                if(n1 > n2) {
                    int temp = n1;
                    n1 = n2;
                    n2 = temp;
                };
                (nodes[n1]->c).push_front(nodes[n2]);
            };
        };

        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;
            for(list<node*>::iterator i = (r->c).begin(); i != (r->c).end(); i++){
                long s = dfs(*i);

                /* 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;
};