Cod sursa(job #915899)

Utilizator fhandreiAndrei Hareza fhandrei Data 15 martie 2013 15:16:47
Problema Ghiozdan Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.32 kb
// Include
#include <fstream>
using namespace std;

// Constante
const int sz = (int)2e4+1;
const int gSZ = 75001;
const int oo = (1<<30)-1;

// Functii
bool used(int where, int who);

// Variabile
ifstream in("ghiozdan.in");
ofstream out("ghiozdan.out");

int num, maxW;

int object[sz];

int best[gSZ];
int father[gSZ];

int maxFound;

bool memoize[gSZ][sz];

// Main
int main()
{
	in >> num >> maxW;

	for(int i=1 ; i<=num ; ++i)
		in >> object[i];

	for(int i=1 ; i<=maxW ; ++i)
		best[i] = oo;

	for(int i=1 ; i<=maxW ; ++i)
	{
		for(int j=1 ; j<=num ; ++j)
		{
			if(object[j] <= i)
			{
				if(best[i-object[j]] < best[i]-1 && !used(i-object[j], j))
				{
					best[i] = best[i-object[j]]+1;
					father[i] = j;
					maxFound = i;
				}
			}
		}
	}

	out << maxFound << ' ';

	int len = 0, temp = maxFound;
	while(father[temp])
	{
		++len;
		temp -= object[father[temp]];
	}

	out << len << '\n';

	while(father[maxFound])
	{
		out << object[father[maxFound]] << '\n';
		maxFound -= object[father[maxFound]];
	}

	in.close();
	out.close();
	return 0;
}

bool used(int where, int who)
{
	if(memoize[where][who])
		return memoize[where][who];
	if(father[where])
	{
		if(who == father[where])
			return memoize[where][who] = true;
		return memoize[where][who] = used(where - object[father[where]], who);
	}
	return memoize[where][who] = false;
}