1111. 数塔

cd106224

DP

//dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + a[i][j];
#include <iostream>
#include <algorithm>
using namespace std;
int a[101][101];
int dp[101][101];
int n;

int main() {
    int num;
    cin >> num;
    while (num--) {
        cin >> n;
        fill(a[0], a[0] + 101 * 101, 0);
        fill(dp[0], dp[0] + 101 * 101, 0);
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j <= i; ++j) {
                cin >> a[i][j];
            }
        }
        for (int i = n - 1; i >= 0; --i) {
            for (int j = 0; j <= i; ++j) {
                dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + a[i][j];
            }
        }
        cout << dp[0][0] << endl;
    }
    return 0;
}
cd106224

DFS

#include <iostream>
#include <algorithm>
using namespace std;
int a[101][101];
int n;
int _min;
void DFS(int index, int sum, int j) {
    if (index > n) {
        return;
    }
    if (index == n) {
        if (sum < _min) {
            _min = sum;
        }
        return;
    }
    DFS(index + 1, sum + a[index][j], j);
    if (index != 0) {
        DFS(index + 1, sum + a[index][j + 1], j + 1);
    }
}

int main() {
    int num;
    cin >> num;
    while (num--) {
        cin >> n;
        _min = 100000000;
        fill(a[0], a[0] + 101 * 101, 0);
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j <= i; ++j) {
                cin >> a[i][j];
            }
        }
        DFS(0, 0, 0);
        cout << _min << endl;
    }
    return 0;
}
爱丽丝_青贝尔克

做半天a不了,后来发现数塔里的向左对应二维数组的向下,向右对应二维数组的向右下。。。

SmallY

感觉这题dfs比较好写

def dfs(L, i, j, N, sum):
    global min
    if i == N-1:
        a = sum + L[i][j]
        min = a if a < min else min
        return
    dfs(L, i+1, j, N, sum+L[i][j])
    dfs(L, i+1, j+1, N, sum+L[i][j])


C = int(input())
for n in range(C):
    N = int(input())
    L = []
    for i in range(N):
        L.append([int(i) for i in input().split()])
    min = 0xffffffff
    dfs(L, 0, 0, N, 0)
    print(min)
Sigurd

这题有毒。。。
样例数据复制进Clion之后,塔的第四行开始读到的数据全是0,交到OJ上就AC了

_纱灯_

自底向上dp

include

using namespace std;

int main()
{
int i,j,N,n,a[105][105];scanf(“%d”,&N);
while(N–)
{
scanf(“%d”,&n);
for(i=0;i<n;++i)
for(j=0;j<=i;++j)
scanf(“%d”,&a[i][j]);
for(i=n-2;i>=0;–i)
for(j=0;j<=i;++j)
a[i][j]+=min(a[i+1][j],a[i+1][j+1]);
printf(“%d\n”,a[0][0]);
}

return 0;

}

MasterKiller

此处Shut down MasterX 记录

siyutao

include

include

include

using namespace std;
int tower[105][105];
int dp[105][105];
int minn, lev;
int main() {
int T;
scanf(“%d”, &T);
while (T > 0) {
scanf(“%d”, &lev);
fill(dp[0], dp[0] + 105 * 105, 0);
for (int i = 1;i <= lev;i++) {
for (int j = 1;j <= i;j++) {
scanf(“%d”, &tower[i][j]);
}
}
// dp入口
for (int i = 1;i <= lev;i++) {
dp[lev][i] = tower[lev][i];
}
for (int i = lev - 1;i >= 1;i–) {
for (int j = i;j >= 1;j–) {
dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + tower[i][j];
}
}
printf(“%d\n”, dp[1][1]);
T–;
}
return 0;
}
和dfs有什么关系?

你当前正在回复 博客/题目
存在问题!