问题描述
有 N N N件物品和一个容量是 V V V的背包,每种物品都有无限件可用。
第 i i i件物品的体积是 v i vi vi,价值是 w i wi wi。
求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。
输出最大价值。
输入格式:
第一行两个整数, N , V , N,V, N,V,用空格隔开,分别表示物品数量和背包容积。
接下来有 N N N行,每行两个整数 v i , w i vi,wi vi,wi,用空格隔开,分别表示第 i i i 件物品的体积和价值。
输出格式:
输出一个整数,表示最大价值。
数据范围
0
<
N
,
V
≤
1000
0<N,V≤1000
0<N,V≤1000
0
<
v
i
,
w
i
≤
1000
0<vi,wi≤1000
0<vi,wi≤1000
输入样例:
4 5
1 2
2 4
3 4
4 5
输出样例:
10
思路
曲线救国的思路,进行优化。
C++朴素代码:
#include <iostream>
using namespace std;
const int N = 1010;
int n, m;
int f[N][N];
int v[N],w[N];
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for(int i = 1; i <= n; i++)
for(int j = 0; j <= m; j++)
for(int k = 0; k * v[i] <= j ; k++)
f[i][j] = max(f[i][j], f[i - 1][j - v[i] * k] + w[i] * k);
cout << f[n][m] << endl;
return 0;
}
注:容易tle
C++优化代码1:
#include <iostream>
using namespace std;
const int N = 1010;
int n, m;
int f[N][N];
int v[N],w[N];
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for(int i = 1; i <= n; i++)
for(int j = 0; j <= m; j++)
{
f[i][j] = f[i - 1][j];
if(j >= v[i]) f[i][j] = max(f[i][j], f[i][j - v[i]] + w[i]);
}
cout << f[n][m] << endl;
return 0;
}
C++优化代码2:
#include <iostream>
using namespace std;
const int N = 1010;
int n, m;
int f[N];
int v[N],w[N];
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for(int i = 1; i <= n; i++)
for(int j = v[i]; j <= m; j++)
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
return 0;
}
Java朴素代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m;
n = sc.nextInt();
m = sc.nextInt();
int[][] f = new int[1010][1010];
int[] v = new int[1010];
int[] w = new int[1010];
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++)
for (int j = 0; j <= m; j++)
for (int k = 0; k * v[i] <= j; k++)
f[i][j] = Math.max(f[i][j], f[i - 1][j - v[i] * k] + w[i] * k);
System.out.println(f[n][m]);
}
}
Java优化代码1:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m;
n = sc.nextInt();
m = sc.nextInt();
int[][] f = new int[1010][1010];
int[] v = new int[1010];
int[] w = new int[1010];
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++)
for (int j = 0; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v[i]) f[i][j] = Math.max(f[i][j], f[i][j - v[i]] + w[i]);
}
System.out.println(f[n][m]);
}
}
Java空间优化代码2:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m;
n = sc.nextInt();
m = sc.nextInt();
int[] f = new int[1010];
int[] v = new int[1010];
int[] w = new int[1010];
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++)
for (int j = v[i]; j <= m; j++)
f[j] = Math.max(f[j], f[j - v[i]] + w[i]);
System.out.println(f[m]);
}
}