1. 程式人生 > >數字三角形(搜尋)

數字三角形(搜尋)

題意:

編寫一個程式計算從頂至底的某處的一條路徑,使該路徑所經過的數字的總和最大。

樣例輸入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

樣例輸出
30

思路:

一開始的想法是從第一個開始搜尋,每次加上相鄰的下一個數,加到最後一層比較每次的最大值,後來發現會超時,最大100層,時間複雜度達到2e100.
後來參考別人的思路,是從下往上搜索,從倒數第二層開始,掃描一個就加上它下面兩個相鄰的數中最大的一個數,這樣子就每一個數是從本身開始向下掃描的最大路徑。

程式碼:

#include <iostream>

using namespace std
; int a[110][110]; int n; void dfs() { for(int i=n-2; i>=0; i--) //從倒數第二層開始,倒數第一層不需要 { for(int j=0; j<=i; j++) //每一層的每個數向下的最大值 { a[i][j] += max(a[i+1][j],a[i+1][j+1]); } } } int main() { while(cin >> n) { for(int i=0; i<n; i++) { for
(int j=0; j<=i; j++) { cin >> a[i][j]; } } dfs(); cout << a[0][0] << endl; } return 0; }
//超時程式碼:59分
#include <iostream>

using namespace std;
int a[110][110];
int n,sum,cnt,temp;
void dfs(int x, int y)
{
    if
(cnt == n) { sum = max(sum,temp); return ; } for(int i=y; i<=y+1; i++) { temp += a[x][i]; cnt++; dfs(x+1,i); cnt--; temp -= a[x][i]; } } int main() { while(cin >> n) { for(int i=0; i<n; i++) { for(int j=0; j<=i; j++) { cin >> a[i][j]; } } sum = -1; cnt = 0; temp = 0; dfs(0,0); cout << sum << endl; } return 0; }