鱼C论坛

 找回密码
 立即注册
查看: 2820|回复: 9

题目67:使用高效算法找到三角形中的最大和。

[复制链接]
发表于 2015-10-14 15:43:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 欧拉计划 于 2015-10-14 15:45 编辑
Maximum path sum II

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

QQ20151014-4@2x.png

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are QQ20151014-5@2x.png altogether! If you could check one trillion QQ20151014-6@2x.png routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

题目:

从以下三角形的顶端开始,向下一行的相邻数字移动,从顶端到底端的最大总和是 23 。

QQ20151014-4@2x.png

也就是 3 + 7 + 4 + 9 = 23。

p067_triangle.txt (14.79 KB, 下载次数: 83) (右键另存为)是一个文本文件,包含了一个一百行的三角形,找出这个三角形中从顶到底的最大和。

注意:这是题目 18 的更难的一个版本。穷举每一种可能的路径是不可行的,因为一共有 QQ20151014-5@2x.png 条可能的路径。就算每秒钟能处理 QQ20151014-6@2x.png 条路径,也需要 200 亿年来处理完所有的路径。存在一个高效的方法来处理这道题。

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-9-25 01:34:05 | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2020-7-2 18:48 编辑
  1. 7273
  2. [Finished in 0.2s]

  3. lst =[
  4. ['59'],
  5. ...,
  6. ['23','33','44','81','80','92','93','75','94','88','23','61','39','76','22','03','28','94','32','06','49','65','41','34','18','23','08','47','62','60','03','63','33','13','80','52','31','54','73','43','70','26','16','69','57','87','83','31','03','93','70','81','47','95','77','44','29','68','39','51','56','59','63','07','25','70','07','77','43','53','64','03','94','42','95','39','18','01','66','21','16','97','20','50','90','16','70','10','95','69','29','06','25','61','41','26','15','59','63','35']]

  7. dic = {'00':0,'01':1,'02':2,'03':3,'04':4,'05':5,'06':6,'07':7,'08':8,'09':9}
  8. lstnew = lst[:]
  9. for x in range(100):
  10.         for j in range(x+1):
  11.                 if lst[x][j] == '00' or lst[x][j] == '01' or lst[x][j] == '02' or lst[x][j] == '03' or lst[x][j] == '04' or lst[x][j] == '05' or lst[x][j] == '06' or lst[x][j] == '07' or lst[x][j] == '08' or lst[x][j] == '09':
  12.                         lstnew[x][j] = dic[lst[x][j]]
  13.                 else:
  14.                         lstnew[x][j] = int(lst[x][j])
  15. for y in range(1,100):
  16.         for z in range(y+1):
  17.                 if z == 0:
  18.                         lstnew[y][z] += lstnew[y-1][z]
  19.                 elif z == y:
  20.                         lstnew[y][z] += lstnew[y-1][z-1]
  21.                 elif lstnew[y-1][z-1] < lstnew[y-1][z]:
  22.                         lstnew[y][z] += lstnew[y-1][z]
  23.                 else:
  24.                         lstnew[y][z] += lstnew[y-1][z-1]
  25. print (max(lstnew[99]))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-1-1 10:33:29 | 显示全部楼层
另外一种,最优化求解的方法(可以适用多路径最优求解):
  1. #coding:utf-8
  2. #initiate:
  3. file=open('triangle.txt')
  4. f=file.read()
  5. file.close()
  6. s=f.split('\n')
  7. triangle = [[]*(i+1) for i in range(100)]
  8. for i in range(100):
  9.     triangle[i]=s[i].split()
  10. for i in range(100):
  11.     for j in range(i+1):
  12.         triangle[i][j]=int(triangle[i][j])
  13. #print (triangle)
  14. visited = [[False]*(i+1) for i in range(100)]
  15. dp = [[0]*(i+1) for i in range(100)]
  16. move = [(1,0),(1,1)]
  17. checklist = [(0,0)]
  18. dp[0][0] = 59

  19. #define method to search the best way:
  20. def findway(x,y):
  21.         if not visited[x][y]:
  22.                 visited[x][y] = True
  23.                 for m in move:
  24.                         nx,ny = x+m[0],y+m[1]
  25.                         if 0<=nx<100 and 0<=ny<=nx:
  26.                                 dp[nx][ny] = max(dp[x][y]+triangle[nx][ny],dp[nx][ny])
  27.                                 checklist.append((nx,ny))

  28. #max9999 is the max price to go:
  29. max9999 = 0

  30. #repeat again and again until the max is stable, that's the answer.
  31. while True:
  32.         for i in range(len(checklist)):
  33.                 findway(checklist[i][0],checklist[i][1])
  34.         if len([(j,k) for j in range(100) for k in range(j) if not visited[j][k]]) == 0:
  35.                 visited = [[False]*(i+1) for i in range(100)]
  36.                 checklist = [(0,0)]
  37.                 if max9999 < max(dp[99]):
  38.                         max9999 = max(dp[99])
  39.                 else:
  40.                         print (max9999)
  41.                         break
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-1-24 10:30:36 | 显示全部楼层
  1. # encoding:utf-8
  2. # 计算三角形最长路径
  3. from time import time
  4. def readFile():
  5.     data = []
  6.     with open('p067_triangle.txt') as f:
  7.         for line in f:
  8.             tmp = [int(x) for x in str(line).replace('\n', '').split(sep=' ')]
  9.             data.append(tmp)
  10.     return data        
  11. def euler067():
  12.     data = readFile()
  13.     for i in range(len(data) - 2, -1, -1):
  14.         for j in range(0, len(data[i])):
  15.             if data[i][j] + data[i + 1][j] > data[i][j] + data[i + 1][j + 1]:
  16.                 data[i][j] = data[i][j] + data[i + 1][j]
  17.             else:
  18.                 data[i][j] = data[i][j] + data[i + 1][j + 1]
  19.     print(data[0][0])         
  20. if __name__ == '__main__':
  21.     start = time()
  22.     euler067()
  23.     print('cost %.6f sec' % (time() - start))
复制代码


7273
cost 0.017002 sec
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-12-5 16:20:20 | 显示全部楼层
data67.csv中数据的格式:
  1. 59
  2. 73,41
  3. 52,40,09
  4. 26,53,06,34
  5. 10,51,87,86,81
  6. 61,95,66,57,25,68
  7. 90,81,80,38,92,67,73
  8. 30,28,51,76,81,18,75,44
  9. ……
复制代码

  1. import csv

  2. nums = []
  3. with open('data67.csv') as f:
  4.     reader = csv.reader(f)
  5.     for row in reader:
  6.         nums.append(row)

  7. list1 = []
  8. i = len(nums)-1
  9. # 先处理最后一行,选择相邻两个数中大的那个,将其位置、数值放入list1列表中
  10. for j in range(i):
  11.     a = nums[i][j]
  12.     b = nums[i][j+1]
  13.     if a > b and [i,j,a] not in list1:
  14.         list1.append([i,j,a])
  15.     elif b > a and [i,j+1,b] not in list1:
  16.         list1.append([i,j+1,b])

  17. # 从倒数第二行开始,依次向上处理
  18. while i > 0:
  19.     dict1 = {}
  20.     i = i-1
  21.     # 将list1中每个数字的上一行的相邻两个(或一个)数字加到字典dict1中
  22.     for each in list1:
  23.         j = each[1]
  24.         if j == 0:          # 处理每行处于第一列的数字
  25.             dict1.setdefault((i,j),[]).append(int(nums[i][j])+int(each[2]))
  26.         elif j == i+1:      # 处理每行处于最后一列的数字
  27.             dict1.setdefault((i,j-1), []).append(int(nums[i][j-1])+int(each[2]))
  28.         else:               # 处理中间的数字,由于中间的数字在上一行都会对应两个相邻数字,所以要增加一种情况
  29.             dict1.setdefault((i, j), []).append(int(nums[i][j])+int(each[2]))
  30.             dict1.setdefault((i, j - 1), []).append(int(nums[i][j-1])+int(each[2]))
  31.     # 将字典转换为列表,并选择较大的那个数值
  32.     list1 = []
  33.     for each in dict1:
  34.         list1.append([each[0], each[1], max(dict1[each])])
  35. print(list1[0][2])
复制代码



7273
0:00:00.015637
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-12-19 11:00:55 | 显示全部楼层
本帖最后由 fc1735 于 2020-2-21 17:01 编辑
  1. from functools import reduce
  2. f = open('67.txt')
  3. t = f.read()
  4. t = list(map(lambda x: list(map(lambda y: int(y), x.split())),
  5.       filter(lambda x: len(x) != 0, t.split('\n'))))

  6. print(max(reduce(lambda x, y: list(map(lambda a, b: a + b, map(max, [0] + x, x + [0]), y)), t)))
复制代码

https://github.com/devinizz/project_euler/blob/master/page02/67.py
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-5 10:19:46 | 显示全部楼层
7273

Process returned 0 (0x0)   execution time : 0.049 s
Press any key to continue.
动态规划(dp)经典题,状态转移方程为

                               
登录/注册后可看大图

  1. #include<iostream>
  2. #include<algorithm>
  3. #include<cstdio>
  4. #include<cstring>
  5. using namespace std;

  6. const int M = 100 + 5;
  7. int a[M][M];
  8. int opt[M][M];

  9. int dp(int i,int j){
  10.   if (opt[i][j] >= 0) return opt[i][j];
  11.   if (i == 100-1) return opt[i][j] = a[i][j];
  12.   return opt[i][j] = a[i][j] + max(dp(i+1,j),dp(i+1,j+1));
  13. }

  14. int main(){
  15.   freopen("i.in","r",stdin);
  16.   memset(opt,-1,sizeof(opt));

  17.   for (int i = 0;i < 100;i++){
  18.     for (int j = 0;j <= i;j++){
  19.       cin >> a[i][j];
  20.     }
  21.   }

  22.   cout << dp(0,0) << endl;
  23.   return 0;
  24. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-9-1 18:02:00 | 显示全部楼层
C++
  1. #include<iostream>
  2. #include<fstream>
  3. #include<vector>
  4. using namespace std;
  5. using vecus = vector<unsigned short>;


  6. unsigned int max(const vecus& v) {
  7.     unsigned int result = 0;

  8.     for (auto i : v) {
  9.         if (i > result) {
  10.             result = i;
  11.         }
  12.     }

  13.     return result;
  14. }


  15. void scan(ifstream& file, vecus& v, size_t count) {
  16.     unsigned short t;

  17.     for (size_t i = 0; i < count; i++) {
  18.         file >> t;
  19.         v[i] = t;
  20.     }
  21. }


  22. void add(const vecus& a, vecus& b) {
  23.     size_t i;
  24.     b[0] += a[0];

  25.     for (i = 1; i < a.size(); i++) {
  26.         b[i] += max(a[i], a[i - 1]);
  27.     }

  28.     b[i] += a[i - 1];
  29. }


  30. int main() {
  31.     ios::sync_with_stdio(false);

  32.     ifstream file("C:\\Users\\WWW\\Desktop\\0\\p067_triangle.txt");
  33.     constexpr static size_t N = 100;
  34.     vecus a(N), b(N);
  35.     scan(file, b, 1);


  36.     for (size_t line = 2; line <= N; line++) {
  37.         swap(a, b);
  38.         scan(file, b, line);
  39.         add(a, b);
  40.     }


  41.     cout << max(b) << endl;
  42.     return 0;
  43. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-2-8 13:33:23 | 显示全部楼层
  1. #include <iostream>
  2. using namespace std;
  3. #define max(x,y) ((x)>(y)?(x):(y))
  4. int Array[]={
  5. #include "p067_triangle.txt"
  6. };
  7. #define width 100
  8. void setmax(int i,int j)
  9. {
  10.     if(j == 0)
  11.         Array[i*(i+1)/2+j] += Array[i*(i-1)/2+j];
  12.     else if(j == i)
  13.         Array[i*(i+1)/2+j] += Array[i*(i-1)/2+j-1];
  14.     else
  15.         Array[i*(i+1)/2+j] += max(Array[i*(i-1)/2+j],Array[i*(i-1)/2+j-1]);
  16. }
  17. int main()
  18. {
  19.     for(int i=1;i<width;i++)
  20.         for(int j=0;j<=i;j++)
  21.             setmax(i,j);
  22.     int maxum = 0;
  23.     for(int i=width*(width-1)/2+0;i<width*(width-1)/2+width;i++)
  24.         if(maxum<Array[i])
  25.             maxum = Array[i];
  26.     cout << maxum;
  27. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-11-14 20:43:30 | 显示全部楼层
  1. import time as t

  2. start = t.perf_counter()

  3. with open('C:/Users/50598/Desktop/p067_triangle.txt', 'r') as f:
  4.     file = f.read().splitlines()
  5.     nums = []
  6.     for each_row in file:
  7.         nums.append([int(each_num) for each_num in each_row.split()])

  8. for i in range(len(nums) - 2, -1, -1):
  9.     for j in range(i + 1):
  10.         if nums[i + 1][j] > nums[i + 1][j + 1]:
  11.             nums[i][j] += nums[i + 1][j]
  12.         else:
  13.             nums[i][j] += nums[i + 1][j + 1]

  14. print(nums[0][0])
  15. print("It costs %f s" % (t.perf_counter() - start))
复制代码



7273
It costs 0.002033 s
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 01:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表