# Preface:

At one noon, we worked on the questions with our classmates from the second grade, after I started the first question. I started paddling, and I didn't even think about hanging up this question, so today I took advantage of my spare time to review and summarize.

# Ideas:

In short, this is a 01 backpack-a better question.
The cost is linked (two-dimensional) or one-dimensional, but my ability is limited ;

## note! The state transition equation must not be written like this:

``````f[i][j]=max(f[i-1][j],f[i-1][j-w[i]+1]+v[i]);
``````

## why? !

### So the correct state transition equation should be this duck:

``````f[i][j]=max(f[i-1][j],f[i-1][max(j-w[i].a,0)+1]+w[i].b);
``````

#### Here a is the hook and b is the value.

Then assign the initial value.
We should assign the impossible situation to the minimum value, namely

`````` f[i]=MAXN,f[i][n+1]=MAXN;
``````

Then f=0 which is the initial state.

## So why sort?

I guess you guys should understand, but I still want to talk about it:
because the items with the greatest joy must be listed first, so they must be sorted.

## note:

### How to deal with the situation of array out of bounds:

1≤N≤2000, 0≤Ai≤N (1≤i≤N), we
can see that there can be about 2000 × 2000 = 4000000 hooks at most. Obviously we can't open so many arrays to transfer one by one, otherwise it will be T .
Through observation, we can see that N is only 2000, which means that only 2000 hooks will be used at most. Therefore, when calculating the number of hooks to exceed 2000, we directly regard the number of hooks in the result as 2000, because 2000 is the limit. Will not affect the answer.

# On the AC code:

``````#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = -1000000000;
int f;
struct leimu {

int a, b;
} w;
bool cmp(leimu i, leimu j) {

return i.a > j.a; }
int ans = -2147483647;
int main() {

int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", &w[i].a, &w[i].b);
sort(w + 1, w + 1 + n, cmp);
for (int i = 0; i <= n; i++) f[i] = MAXN, f[i][n + 1] = MAXN;
f = 0;
for (int i = 1; i <= n; i++) {

for (int j = 0; j <= n; j++) {

f[i][j] = max(f[i - 1][j], f[i - 1][max(j - w[i].a, 0) + 1] +
w[i].b);  // f[i][j]表示前i件物品在有j个挂钩的情况下的最大价值
}
}
for (int i = 0; i <= n; i++) ans = max(ans, f[n][i]);  //每个钩子都有可能
printf("%d", ans);
return 0;
}
``````

# summary:

Dynamic programming each question are worth to analyze, to understand the meaning of each state transition equation, it can be more Gangster powerful.

### Guess you like

Origin blog.csdn.net/C202207LYX/article/details/106892379
Recommended
Ranking
Daily