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 5e361fd

Browse files
1770: MLE & TLE
1 parent aeaa024 commit 5e361fd

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright (C) 2022, Saul Lawliet <october dot sunbathe at gmail dot com>
3+
* All rights reserved.
4+
*
5+
* 一看这是一个动态规划的问题, 分析后发现需要画一个二叉树的表格?
6+
* 头一次遇到这样的问题, 兴奋极了, 一顿操作下来
7+
* 又是 Memory Limit Exceeded, 又是 Time Limit Exceeded 的
8+
*
9+
* 下个文件再从头开始...
10+
*/
11+
12+
#include "c/data-structures/array.h"
13+
#include "c/test.h"
14+
15+
struct Cell{
16+
int v; // value
17+
int p; // [p, q]
18+
int q;
19+
};
20+
21+
int maximumScore(int *nums, int numsSize, int *multipliers, int multipliersSize) {
22+
// 构建二叉树型表格
23+
struct Cell **table = malloc(sizeof(struct Cell *) * multipliersSize);
24+
for (int i = 0; i < multipliersSize; i++) {
25+
table[i] = malloc(sizeof(struct Cell) * (2 << i));
26+
}
27+
28+
for (int i = 0; i < multipliersSize; i++) {
29+
for (int j = 0; j < 1 << i; j++) {
30+
struct Cell cell = i == 0 ? (struct Cell){0, 0, numsSize - 1} : table[i - 1][j];
31+
table[i][2 * j] = (struct Cell){cell.v + nums[cell.p] * multipliers[i], cell.p + 1, cell.q};
32+
table[i][2 * j + 1] = (struct Cell){cell.v + nums[cell.q] * multipliers[i], cell.p, cell.q - 1};
33+
}
34+
}
35+
36+
int max = INT32_MIN;
37+
for (int i = 0; i < 1 << multipliersSize; i++) {
38+
if (table[multipliersSize-1][i].v > max) {
39+
max = table[multipliersSize-1][i].v;
40+
}
41+
}
42+
43+
for (int i = 0; i < multipliersSize; i++) {
44+
free(table[i]);
45+
}
46+
free(table);
47+
48+
return max;
49+
}
50+
51+
void test(int expect, const char *nums, const char *multipliers) {
52+
arrayEntry *e1 = arrayParse1D(nums, ARRAY_INT);
53+
arrayEntry *e2 = arrayParse1D(multipliers, ARRAY_INT);
54+
55+
EXPECT_EQ_INT(expect, maximumScore(arrayValue(e1), arraySize(e1), arrayValue(e2), arraySize(e2)));
56+
57+
arrayFree(e2);
58+
arrayFree(e1);
59+
}
60+
61+
int main(void) {
62+
test(14, "[1,2,3]", "[3,2,1]");
63+
test(102, "[-5,-3,-3,-2,7,1]", "[-10,-5,3,4,6]");
64+
65+
return testOutput();
66+
}

0 commit comments

Comments
(0)

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