//Everything you see exists together in a delicate balance.//
输入样例:
代码块:(动态规划)
#include <stdio.h>
#include <stdlib.h>
//比较函数。
int max(int a,int b){
return a>b?a:b;
}
int main(int argc, char *argv[])
{
int n,a[1000][1000]={0};
scanf("%d",&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++){
scanf("%d",&a[i][j]);
}
//将上一行对应位置的较大值加到下一行
for(int i=2;i<=n;i++){
for(int j=1;j<=i;j++){
a[i][j]+=max(a[i-1][j],a[i-1][j-1]);
}
}
//n奇数行左右移动次数不相差1必定在中间位置; 奇数情况下(n+1)/2=n/2+1
//n偶数行,最终在n/2和n/2+1之间
//两种判断合在一起判断,n/2和(n+1)/2对int型等价,但后者能同时判断奇数行和偶数行。
printf("%d",max(a[n][(n+1)/2],a[n][n/2+1]));
return 0;
}
代码块:dfs(会超时)
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 110;
int n;
int maxnum;
int note[maxn] = { 0 }, left1 = 0, right1 = 0, pos = 1;
int a[maxn][maxn];
void dfs(int x, int left, int right) {
if (x == n) { // 递归边界
if (abs(left - right) > 1) return;
note[x] = a[x][1 + right]; //
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += note[i];
}
if (sum > maxnum) maxnum = sum; // 刷新最大值
return;
}
note[x] = a[x][1 + right]; // 记录第x层的数字
dfs(x + 1, left + 1, right);
dfs(x + 1, left, right + 1);
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cin >> a[i][j];
}
}
dfs(1,0,0);
cout << maxnum << endl;
return 0;
}