Cod sursa(job #986952)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 19 august 2013 20:49:26
Problema Mese Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
  
const string file = "mese";
  
const string infile = file + ".in";
const string outfile = file + ".out";

int N;
int S;
int Sol;

vector<vector<int> > G;
vector<int> age;
vector<int> ageSum;


int pred(const int a, const int b)
{
	return ageSum[a] < ageSum[b];
}

void DFS()
{
	stack<int> s;
	vector<bool> seen;
	seen.resize(N + 1);
	ageSum.resize(N + 1);

	s.push(0);

	while(s.empty() == false)
	{
		int nod = s.top();

		if(seen[nod] == false)
		{
			seen[nod] = true;

			for(vector<int>::iterator itr = G[nod].begin();
				itr != G[nod].end();
				itr++)
			{
				s.push(*itr);
			}
		}
		else
		{
			ageSum[nod] = age[nod];
			s.pop();
			for(vector<int> ::iterator itr = G[nod].begin();
				itr != G[nod].end();
				itr++)
			{
				ageSum[nod] += ageSum[*itr];
			}

			if(ageSum[nod] > S)
			{
				sort(G[nod].begin(), G[nod].end(), pred);
			}
			while(ageSum[nod] > S)
			{
				Sol++;
				ageSum[nod] -= ageSum[G[nod].back()];
				G[nod].pop_back();
			}
		}
	}
}


int main()
{
	ifstream fin(infile.c_str());

	fin >> N >> S;

	G.resize(N + 1);
	age.resize(N + 1);

	for(int i = 0; i < N; i++)
	{
		int x, y;
		fin >> x >> y;
		age[i + 1] = y;
		G[x].push_back(i + 1);
	}
	fin.close();

	DFS();
	
	ofstream fout(outfile.c_str());
	fout << Sol + 1 << "\n";
	fout.close();
}