Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit aa22b80

Browse files
添加 背包理论基础01-2.mc C语言版本
1 parent 4defb3d commit aa22b80

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎problems/背包理论基础01背包-2.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,39 @@ function test () {
315315
test();
316316
```
317317

318+
### C
319+
```c
320+
#include <stdio.h>
321+
#include <string.h>
322+
323+
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
324+
#define ARR_SIZE(arr) ((sizeof((arr))) / sizeof((arr)[0]))
325+
#define BAG_WEIGHT 4
326+
327+
void test_back_pack(int* weights, int weightSize, int* values, int valueSize, int bagWeight) {
328+
int dp[bagWeight + 1];
329+
memset(dp, 0, sizeof(int) * (bagWeight + 1));
330+
331+
int i, j;
332+
// 先遍历物品
333+
for(i = 0; i < weightSize; ++i) {
334+
// 后遍历重量。从后向前遍历
335+
for(j = bagWeight; j >= weights[i]; --j) {
336+
dp[j] = MAX(dp[j], dp[j - weights[i]] + values[i]);
337+
}
338+
}
339+
340+
// 打印最优结果
341+
printf("%d\n", dp[bagWeight]);
342+
}
343+
344+
int main(int argc, char** argv) {
345+
int weights[] = {1, 3, 4};
346+
int values[] = {15, 20, 30};
347+
test_back_pack(weights, ARR_SIZE(weights), values, ARR_SIZE(values), BAG_WEIGHT);
348+
return 0;
349+
}
350+
```
318351
319352
320353
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /