代码如下:
//三角形自顶向下求最大最小路径和
#include <stdio.h>
#include<string.h>
int num[100][100];
//核心代码:
int maxsum(int N)
{
int k, p;
for (k = N - 2; k >= 0; k--)
{
for (p = 0; p <= k; p++)
{
num[k][p] = num[k + 1][p + 1] > num[k + 1][p] ? num[k + 1][p + 1] + num[k][p] : num[k + 1][p] + num[k][p];
}
}
return num[0][0];
}
int minsum(int N)
{
int k, p;
for (k = N - 2; k >= 0; k--)
{
for (p = 0; p <= k; p++)
{
num[k][p] = num[k + 1][p + 1] < num[k + 1][p] ? num[k + 1][p + 1] + num[k][p] : num[k + 1][p] + num[k][p];
}
}
return num[0][0];
}
int main()
{
int n;
/*
用EOF作为文件结束标志 C语言中实际上 EOF 的值通常为 -1
scanf("%d",&n) != EOF"相当于"scanf("%d",&n) != EOF",或"~scanf("%d",&n)",或"scanf("%d",&n) == 1
*/
while (scanf_s("%d", &n) != EOF && n)
{
memset(num, 0, sizeof(num));
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)//j<=i!!!
{
scanf_s("%d", &num[i][j]);
}
}
printf("-----------------------------------------\n");
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)
{
printf("%d ", num[i][j]);
}
printf("\n");
}
printf("数字总和最大:%d\n", maxsum(n));
break;
}
while (scanf_s("%d", &n) != EOF && n)
{
memset(num, 0, sizeof(num));
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)//j<=i!!!
{
scanf_s("%d", &num[i][j]);
}
}
printf("-----------------------------------------\n");
for (i = 0; i < n; i++)
{
for (j = 0; j <= i; j++)
{
printf("%d ", num[i][j]);
}
printf("\n");
}
printf("数字总和最小:%d\n", minsum(n));
}
return 0;
}
运行截图: