您的位置:首页 > 其它

普及练习场 动态规划的背包问题 金明的预算方案

2018-01-13 21:25 363 查看
题目链接

题意理解

首先说一下,这道题目我简直WA疯了。

WA点主要有这么几个:

细节。在输入的时候,如果q>0,那么这时候应该是第q个货物的附加货物。

关键部分。状态转移方程少掉了一个状态。这个题目应该有四个状态转移方程:只选主货物;选主货物与第一个附加货物;选主货物与第二个附加货物;选主货物与第一个附加货物与第二个附加货物。我漏掉了<选主货物与第二个附加货物>这个状态。

关键部分。状态转移方程写错了。实际上,不能用dp[i][j]表示第i个货物,因为我这里把附加货物考虑进来了,就不是一个货物的问题了。

代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Thing {
int vm;
int pm;
int v1;
int p1;
int v2;
int p2;
public Thing() {
this(0, 0);
}
public Thing(int vm, int pm) {
this.vm = vm;
this.pm = pm;
this.v1 = 0;
this.p1 = 0;
this.v2 = 0;
this.p2 = 0;
}

public void print(int i) {
System.out.println(i + " " + vm + " " + pm + " " + v1 + " " + p1 + " " + v2 + " " + p2);
}
}
public class Main {
static int N, m;
static Thing[] things;
static int[] dp;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
N = fs.nextInt();
N /= 10;
m = fs.nextInt();
things = new Thing[m + 1];
for(int i = 0; i <= m; i++) {
things[i] = new Thing();
}
dp = new int[N + 1];
for(int i = 1; i <= m; i++) {
int v, p, q;
v = fs.nextInt();
v /= 10;
p = fs.nextInt();
q = fs.nextInt();
if(q == 0) {
things[i].vm = v;
things[i].pm = p * v;
}
if(q > 0) {
if(things[q].p1 == 0) {
things[q].v1 = v;
things[q].p1 = p * v;
} else {
things[q].v2 = v;
things[q].p2 = p * v;
}
}
}

int max = -1;
for(int i = 1; i <= m; i++) {
if(things[i].pm == 0) {
continue;
}
for(int j = N; j >= 1; j--) {
int t1 = things[i].vm;
int t2 = things[i].pm;
if(j >= t1) {
dp[j] = Math.max(dp[j], dp[j-t1] + t2);
}
int t3 = things[i].vm + things[i].v1;
int t4 = things[i].pm + things[i].p1;
if(j >= t3) {
dp[j] = Math.max(dp[j], dp[j-t3] + t4);
} else {
dp[j] = dp[j];
}
int t7 = things[i].vm + things[i].v2;
int t8 = things[i].pm + things[i].p2;
if(j >= t7) {
dp[j] = Math.max(dp[j], dp[j-t7] + t8);
} else {
dp[j] = dp[j];
}
int t5 = things[i].vm + things[i].v1 + things[i].v2;
int t6 = things[i].pm + things[i].p1 + things[i].p2;
if(j >= t5) {
dp[j] = Math.max(dp[j], dp[j-t5] + t6);
} else {
dp[j] = dp[j];
}
if(dp[j] > max) {
max = dp[j];
}
}
}
System.out.println(max * 10);
}

public static class FastScanner {
private BufferedReader br;
private StringTokenizer st;

public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}

public String nextToken() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
// TODO: handle exception
}
}
return st.nextToken();
}

public int nextInt() {
return Integer.valueOf(nextToken());
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: