小美有一个矩形蛋糕,共分成了n行m列,共n*m个区域,每个区域是一个小正方形,已知蛋糕每个区域都有一个美味度,想切一刀把蛋糕切成两份,自己吃一部分,小团吃一部分,小美希望两个人吃的美味度之和尽可能接近
以下是使用C语言编写的代码,用于计算切割矩形蛋糕后两份美味度之差的最小值:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, m;
printf("请输入矩形蛋糕的行数n和列数m:");
scanf("%d %d", &n, &m);
int **cake = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
cake[i] = (int *)malloc(m * sizeof(int));
}
printf("请依次输入每个区域的美味度:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &cake[i][j]);
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
sum += cake[i][j];
}
}
int halfSum = sum / 2;
int **dp = (int **)malloc((halfSum + 1) * sizeof(int *));
for (int i = 0; i <= halfSum; i++) {
dp[i] = (int *)malloc((m + 1) * sizeof(int));
}
for (int i = 0; i <= halfSum; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= m; i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= halfSum; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = dp[i][j - 1];
if (i >= cake[0][j - 1] && dp[i][j] < dp[i - cake[0][j - 1]][j - 1] + cake[0][j - 1]) {
dp[i][j] = dp[i - cake[0][j - 1]][j - 1] + cake[0][j - 1];
}
}
}
int maxSum = dp[halfSum][m];
int minDiff = sum - 2 * maxSum;
printf("|S1 - S2|的最小值为:%d\n", minDiff);
for (int i = 0; i < n; i++) {
free(cake[i]);
}
free(cake);
for (int i = 0; i <= halfSum; i++) {
free(dp[i]);
}
free(dp);
return 0;
}
```
这段代码使用动态规划的思想,通过二维数组dp来记录每个美味度和的最大值。最后计算出两份美味度之差的最小值,并输出结果。
请注意,这段代码假设输入的数据合法,即n和m为正整数,每个区域的美味度为非负整数。在实际使用中,可能需要添加一些输入验证的代码来确保输入的正确性。
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, m;
printf("请输入矩形蛋糕的行数n和列数m:");
scanf("%d %d", &n, &m);
int **cake = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
cake[i] = (int *)malloc(m * sizeof(int));
}
printf("请依次输入每个区域的美味度:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &cake[i][j]);
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
sum += cake[i][j];
}
}
int halfSum = sum / 2;
int **dp = (int **)malloc((halfSum + 1) * sizeof(int *));
for (int i = 0; i <= halfSum; i++) {
dp[i] = (int *)malloc((m + 1) * sizeof(int));
}
for (int i = 0; i <= halfSum; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= m; i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= halfSum; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = dp[i][j - 1];
if (i >= cake[0][j - 1] && dp[i][j] < dp[i - cake[0][j - 1]][j - 1] + cake[0][j - 1]) {
dp[i][j] = dp[i - cake[0][j - 1]][j - 1] + cake[0][j - 1];
}
}
}
int maxSum = dp[halfSum][m];
int minDiff = sum - 2 * maxSum;
printf("|S1 - S2|的最小值为:%d\n", minDiff);
for (int i = 0; i < n; i++) {
free(cake[i]);
}
free(cake);
for (int i = 0; i <= halfSum; i++) {
free(dp[i]);
}
free(dp);
return 0;
}
```
这段代码使用动态规划的思想,通过二维数组dp来记录每个美味度和的最大值。最后计算出两份美味度之差的最小值,并输出结果。
请注意,这段代码假设输入的数据合法,即n和m为正整数,每个区域的美味度为非负整数。在实际使用中,可能需要添加一些输入验证的代码来确保输入的正确性。