F - Coins (可行性揹包)

Whuacmers use coins.They have coins of value A1,A2,A3...An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn't know the exact price of the watch. 

You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony's coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.
InputThe input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.OutputFor each test case output the answer on a single line.Sample Input
3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0
Sample Output
8
4
快速的(0.5秒左右)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;
const int N=1e5+10;
int used[N],num[110],v[110];
bool dp[N];

int main(void)
{
	int n, m;
	ios::sync_with_stdio(false);
	while(cin>>n>>m)
	{
		if(n==0&&m==0)
		break;
		for(int i=1; i <= n; ++i)
		cin>>v[i];
		for(int i=1; i<=n; ++i)
		cin>>num[i];
		for(int i=1;i<=m;++i) //!!m 
		dp[i]=false;
		dp[0]=true;
		
		int res=0;
		for(int i=1;i<=n;++i)
		{
			memset(used,0,sizeof(used));
			for(int j=v[i];j<=m;++j)
			{
				if(!dp[j]&&dp[j-v[i]]&&used[j-v[i]]<num[i])
				{  //條件:dp[j]之前未達到過且dp[j-v[i]]能到達且之前的使用次數還未超過限制 
					dp[j]=true;
					used[j]=used[j-v[i]]+1;
					res++;
				}
			}
		}
		cout<<res<<endl;
	}
	return 0;
}
慢速的(差不多3秒)(轉換成01揹包):
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e6;
const int INF=0x3f3f3f3f;
int dp[N],v[N];

int main()
{
    int n, m;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
        break;
        int tmp_w[110],tmp_v[110];
        for(int i=1;i<=n;i++)
        {
            cin>>tmp_v[i];
        }
        for(int i=1;i<=n;i++)
        {
            cin>>tmp_w[i];
        }
        int cnt=0;
        for(int i=1;i<=n;i++)
        {
            int k=1;
            while(k<tmp_w[i])
            {
                v[++cnt]=k*tmp_v[i];
                tmp_w[i]-=k;
                k<<=1;
            }
            if(tmp_w[i]>0)
            {
                v[++cnt]=tmp_v[i]*tmp_w[i];
            }
        }
        for(int i=1;i<=m;i++)
        dp[i]=-INF;
        for(int i=1;i<=cnt;i++)
        {
            for(int j=m;j>=v[i];j--)
            {
                if(dp[j]<dp[j-v[i]]+v[i])
                dp[j]=dp[j-v[i]]+v[i];
            }
        }
        int res=0;
        for(int i=1;i<=m;i++)
        {
            if(dp[i]>0)
            res++;
        }
        cout<<res<<endl;
    }
	return 0;
}




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