Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Re:此题N^2的DP怎么做呢?我只会O(N*货币净重量)的DP

Posted by freshvictor at 2011-05-21 16:47:37 on Problem 1384
In Reply To:此题N^2的DP怎么做呢?我只会O(N*货币净重量)的DP Posted by:dongshanluo at 2007-10-12 10:20:47
// BNU_1503.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include <string.h>
#include <math.h>

const int MAXSIZE	= 50004;
const int MAXWEIGH	= 10014;
const int MAXINF	= 1e6;

template<class T>
T max(const T &a, const T &b){return a> b? a: b;}
template<class T>
T min(const T &a, const T &b){return a< b? a: b;}

int nT, wE, wF, nSum;
int pP[MAXSIZE], pW[MAXSIZE];

int knapsack()
{
	int cm[MAXWEIGH];
	int i, j, weigh;
	memset(cm, MAXINF, sizeof(cm));	cm[0] = 0;
	weigh = wF - wE;
	// 开始计算
	for (i = 1; i <= nSum; i++){
		for (j = pW[i]; j <= weigh; j++){
			cm[j] = min(cm[j], cm[j - pW[i]]+ pP[i]);
		}
	}
	return cm[weigh];
}

int main()
{
	int i, k, t, ni, ip, iw;
	int weigh, rst;
	scanf("%d", &nT);
	while (nT--)
	{
		scanf("%d%d%d", &wE, &wF, &ni);
		weigh = wF- wE;
		nSum = 1;
		for (i = 1; i <= ni; i++){
			scanf("%d%d", &ip, &iw);
			// 把第i种物品拆成费用为c[i]*2^k、价值为w[i]*2^k的若干件物品,其中k满足c[i]*2^k<=weigh
			t = 1; k = weigh;
			while (k >= t){
				pP[nSum] = t* ip;
				pW[nSum] = t* iw;
				k -= t;
				t *= 2;
				nSum++;
			}
			if (k) {
				pP[nSum] = k* ip;
				pW[nSum] = k* iw;
			}
		}
		rst = knapsack();
		if (rst < MAXINF)	printf("The minimum amount of money in the piggy-bank is %d.\n", rst);
		else				printf("This is impossible.\n");

	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator