poj 2063 投資 完全揹包

有時候吧,越是看起來簡單的題通過可能還不容易

題意:給定一定數額的金錢(最大1000000),注意是起始錢數,以後滾動起來可能很大

買各種投資產品,每種有費用和對應的盈利

求若干年後最大收益

解法:

              總金錢視爲揹包的體積,每種收益作爲價值,花費作爲體積,完全揹包問題

關鍵點:

             1.一上來RA兩次,顯然數組不夠大,滾動起來數據巨大。(所以啊別看簡單)

             2.擴大數組之後,仍然不夠大,顯然光增大maxn是無用的

             3.看了解題報告,發現原來除以1000減少錢的數量,大量減少內存(在揹包計算的過程中中間數組)

             4.maxn取的太大,TLE了兩次

             5.改小maxn才通過

             另外,每次滾動的時候從cost[i]開始會比較好一些,這樣減少大量的不必要計算和判斷

             for(j = 0; j <= curMoney; j++)

            {

                   if(j >= cost[i] {...}

            }

            for(j = cost[i]; j <= curMoney; j++)

AC不僅僅要算法,要考慮問題周全,要綜合各方面

             

#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <queue>
using namespace std;

///宏定義
const int  INF = 990000000;
const int maxn = 250100 ;
const int MAXN = maxn;
///全局變量 和 函數
int max(int a, int b)
{
	return a > b ? a : b;
}

int cost[maxn];
int benefit[maxn];
int f[maxn];
int N, d;
int years, V;
int main()
{
	///變量定義
	int i, j;
	scanf("%d", &N);
	int cases = 1;
	while(N--)
	{
		scanf("%d %d", &V, &years);
		scanf("%d", &d);
		for (i = 0; i < d; i++)
		{
			scanf("%d %d", &cost[i], &benefit[i]);
			cost[i] /= 1000; //每種價值除以1000
		}

		int curMoney;
		for (int loop = 0; loop < years; loop++)
		{
			curMoney = V / 1000;	//首先呢,把當前錢除以1000,因爲cost除以了1000,但是benefit沒有除以1000,注意
			memset(f, 0, sizeof(f));			
			//0-1揹包經典求解
			for (i = 0; i < d; i++)
			{
				for (j = cost[i]; j <= curMoney; j++)
				{
					if (j >= cost[i])
					{
						if (f[j] < f[j - cost[i]] + benefit[i])
						{
							f[j] = f[j - cost[i]] + benefit[i];
						}
					}
				}			
			}
			V += f[curMoney];
		}
		int ans = V;
		printf("%d\n", ans);
	}
	
	///結束
	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章