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.
3 10 1 2 4 2 1 1 2 5 1 4 2 1 0 0Sample 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;
}