AgPro

导航

经典DP-P1015

#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;

int p[300], d[300];
int s[300];//s[i] = p[i] - d[i];
int f[30][840];
int path[30][840];
int c[30]; //choose jury

bool isvalid(int j, int k, int i) //line j, insert i, sum pi+di=k
{
	for (int q=j; q >= 1; q--) //i never been used 
	{
		if (path[q][k] == i)
			return false;
		else
			k -= s[path[q][k]];
	}
	return true;
}

int com(const void* a, const void* b) 
{
	return *(int*)a - *(int*)b;
}

ifstream in("in.txt");
#define cin in

int main()
{
	int n, m, i, j, k, count, zero, pp, dp, start, temp;
	

	count = 0;
	while (true)
	{
		cin >> n >> m;
		if (n==0 || m==0) 
		{
			break;
		}
		for (i=1; i <= n; i++) 
		{
			cin >> p[i] >> d[i];
			s[i] = p[i] - d[i];
		}
		memset(f, -1, sizeof(f));
		memset(path, 0, sizeof(path));
		zero = m * 20;
		f[0][zero] = 0;
		for (j=0; j < m; j++) // the number of jury members 0->m-1
		{
			for (k=0; k <= zero*2; k++) // k is all possible sum of p[i] + d[i];
			{
				if (f[j][k] >= 0) 
				{
					for (i=1; i <= n; i++) //the number of candidates  1->n
					{
						temp = f[j][k] + p[i] + d[i];
						if (f[j+1][k+s[i]] < temp && isvalid(j, k, i)) 
						{
							path[j+1][k+s[i]] = i;  //line j => line j+1
							f[j+1][k+s[i]] = temp;
						}
					}
				}
			}
		}
		for (k=0; k <= zero; k++)
		{
			if (f[m][zero-k]!=-1 || f[m][zero+k]!=-1) // choose minimal abs(zero-k)
			{
				start = f[m][zero-k] > f[m][zero+k] ? zero-k : zero+k;// if have zero-k and zero+k, choose the one which have larger sum
				break;
			}
		}

		cout << "Jury #" << ++count << endl;
		pp = (f[m][start]+(start-zero))/2; //pp-dp = start-zero
		dp = (f[m][start]-(start-zero))/2; //pp+dp = f[m][start]
		cout << "Best jury has value " << pp <<" for prosecution and value " << dp << " for defence:" << endl;
		for(j=m; j >= 1; j--)
		{
			c[j-1] = path[j][start];
			start -= s[c[j-1]];
		}
		qsort(c, m, sizeof(int), com);
		for (j=0; j < m; j++) 
			cout << " " << c[j];
		cout << endl << endl;
	}
	return 0;
}

posted on 2010-06-29 10:52  AgPro  阅读(405)  评论(0编辑  收藏  举报