Cod sursa(job #2078195)

Utilizator freak93Adrian Budau freak93 Data 29 noiembrie 2017 02:06:54
Problema Mese Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class Tree {
  public:
    Tree(int size):
        m_edges(size),
        m_value(size)
    {
    }

    void set_value(int node, int value) {
        m_value[node] = value;
    }

    void set_root(int node) {
        m_root = node;
    }

    void add_edge(int from, int to) {
        m_edges[from].push_back(to);
    }

    int answer(int S) const {
        return answer(m_root, S).first + 1;
    }

  private:
    pair<int, int> answer(int node, int S) const {
        int many = 0, total = m_value[node];
        vector<int> values;
        values.reserve(m_edges[node].size());
        for (auto &x : m_edges[node]) {
            auto p = answer(x, S);
            many += p.first;
            values.push_back(p.second);
        }

        sort(values.begin(), values.end());
        for (auto &v : values) {
            if (total + v > S)
                ++many;
            else
                total += v;
        }
        return make_pair(many, total);
    }

    vector< vector<int> > m_edges;
    vector<int> m_value;
    int m_root;
};

int main() {
    ifstream cin("mese.in");
    ofstream cout("mese.out");

    int N, S; cin >> N >> S;
    Tree T(N);
    for (int i = 0; i < N; ++i) {
        int x, y; cin >> x >> y;
        if (x != 0)
            T.add_edge(x - 1, i);
        else
            T.set_root(i);
        T.set_value(i, y);
    }

    cout << T.answer(S) << "\n";
}