输入样例
4 5
1 2
2 4
3 4
4 5
输出样例:
10
二维暴力写法:
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 #include<map>
7 #include<set>
8 #include<vector>
9 #include<sstream>
10 using namespace std;
11 #define ll long long
12 const int inf=99999999;
13 const int mod=1e9+7;
14
15 const int maxn=1000+10;
16
17 int value[maxn];//价值
18 int capacity[maxn];//体积
19
20 int dp[1010][maxn];//完全背包
21
22 int main()
23 {
24 ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
25
26 int n,v;//n件物品,最大容量v
27 cin>>n>>v;
28
29 for(int i=0;i<n;i++)
30 cin>>capacity[i]>>value[i];
31
32 memset(dp,0,sizeof(dp));
33
34 for(int i=0;i<n;i++)
35 {
36 for(int j=0;j<=v;j++)
37 {
38 for(int k=0;k*capacity[i]<=j;k++)
39 {
40 dp[i+1][j]=max(dp[i+1][j],dp[i][j-k*capacity[i]]+k*value[i]);
41 }
42 }
43 }
44
45 cout<<dp[n][v]<<endl;
46
47 return 0;
48 }
二维优化写法:
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 #include<map>
7 #include<set>
8 #include<vector>
9 #include<sstream>
10 using namespace std;
11 #define ll long long
12 const int inf=99999999;
13 const int mod=1e9+7;
14
15 const int maxn=1000+10;
16
17 int value[maxn];//价值
18 int capacity[maxn];//体积
19
20 int dp[1010][maxn];//完全背包 优化
21
22 int main()
23 {
24 ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
25
26 int n,v;//n件物品,最大容量v
27 cin>>n>>v;
28
29 for(int i=0;i<n;i++)
30 cin>>capacity[i]>>value[i];
31
32 memset(dp,0,sizeof(dp));
33
34 for(int i=0;i<n;i++)
35 {
36 for(int j=0;j<=v;j++)
37 {
38 if(j<capacity[i])
39 dp[i+1][j]=dp[i][j];
40 else
41 {
42 if(dp[i][j]>dp[i+1][j-capacity[i]]+value[i])
43 dp[i+1][j]=dp[i][j];
44 else
45 dp[i+1][j]=dp[i+1][j-capacity[i]]+value[i];
46 }
47 }
48 }
49
50 cout<<dp[n][v]<<endl;
51
52 return 0;
53 }
一维优化写法:
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 #include<map>
7 #include<set>
8 #include<vector>
9 #include<sstream>
10 using namespace std;
11 #define ll long long
12 const int inf=99999999;
13 const int mod=1e9+7;
14
15 const int maxn=1000+10;
16
17 int value[maxn];//价值
18 int capacity[maxn];//体积
19
20 int dp[maxn];//完全背包 一维优化
21
22 int main()
23 {
24 ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
25
26 int n,v;//n件物品,最大容量v
27 cin>>n>>v;
28
29 for(int i=0;i<n;i++)
30 cin>>capacity[i]>>value[i];
31
32 memset(dp,0,sizeof(dp));
33
34 for(int i=0;i<n;i++)
35 {
36 for(int j=capacity[i];j<=v;j++)
37 {
38 //if(j>=capacity[i])//由循环,j一定大于等于capacity[i]
39 dp[j]=max(dp[j],dp[j-capacity[i]]+value[i]);
40 }
41 }
42
43 cout<<dp[v]<<endl;
44
45 return 0;
46 }