python编写PAT甲级 1007 Maximum Subsequence Sum

wenzongxiao1996

2019.4.3

题目

Given a sequence of K integers { N​1, N2, ..., N​K}. A continuous subsequence is defined to be { N​i, N​i+1, ..., N​j} where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10

-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

暴力解法(超时了)

  1. def seq_sum(s):
  2. """求序列的所有元素之和"""
  3. result = 0
  4. for i in range(len(s)):
  5. result += s[i]
  6. return result
  7. def main():
  8. n = int(input())
  9. seq = [int(i) for i in input().split()]
  10. max = -1
  11. pos_i = 0
  12. pos_j = n-1
  13. for i in range(n):
  14. for j in range(i,n):
  15. sum_temp = seq_sum(seq[i:j+1])
  16. if sum_temp > max:
  17. max = sum_temp
  18. pos_i = i
  19. pos_j = j
  20. if max < 0:
  21. print(0,seq[pos_i],seq[pos_j])
  22. else:
  23. print(max,seq[pos_i],seq[pos_j])
  24. if __name__ == '__main__':
  25. main()

分治法

  1. def division_solution(seq,left,right):
  2. if left == right: # 递归出口
  3. if seq[left] >= 0:
  4. return left,right,seq[left]
  5. else:
  6. return left,right,-1
  7. center = (left+right)//2 # 地板除
  8. # 从中间到左边的最大子串
  9. sum_left = 0
  10. max_sum_left = -1 # 一定要设为负数
  11. pos_left = left # 要返回下标
  12. for i in range(left,center+1)[::-1]: # 反向迭代
  13. sum_left += seq[i]
  14. if sum_left >= max_sum_left:
  15. max_sum_left = sum_left
  16. pos_left = i
  17. # 从中间到右边的最大子串
  18. sum_right = 0
  19. max_sum_right = -1 # 一定要设为负数
  20. pos_right = right # 要返回下标
  21. for i in range(center+1,right+1):
  22. sum_right += seq[i]
  23. if sum_right > max_sum_right:
  24. max_sum_right = sum_right
  25. pos_right = i
  26. # 递归求解左右两个子问题
  27. i_left,j_left,max_left_sum = division_solution(seq,left,center)
  28. i_right,j_right,max_right_sum = division_solution(seq,center+1,right)
  29. if max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) < 0:
  30. return left,right,-1
  31. else:
  32. if max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) == max_left_sum:
  33. return i_left,j_left,max_left_sum
  34. elif max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) == max_right_sum:
  35. return i_right,j_right,max_right_sum
  36. else:
  37. return pos_left,pos_right,max_sum_left+max_sum_right
  38. def main():
  39. n = int(input())
  40. seq = [eval(i) for i in input().split()]
  41. i,j,sum_max = division_solution(seq,0,n-1)
  42. if sum_max < 0:
  43. print(0,seq[0],seq[-1])
  44. else:
  45. print(sum_max,seq[i],seq[j])
  46. if __name__ == '__main__':
  47. main()

动态规划

  1. def main():
  2. n = int(input())
  3. seq = [eval(i) for i in input().split()]
  4. sum_max = -1
  5. pos_i = 0
  6. pos_i_temp = 0 # 最大子序列的左下标不能随意更改,只有找到了更大的子串才能改,用这个变量先保存着当前寻找的子串的左下标
  7. pos_j = n-1
  8. sum_temp = 0
  9. for i in range(n):
  10. sum_temp += seq[i]
  11. if sum_temp > sum_max:
  12. sum_max = sum_temp
  13. pos_j = i
  14. pos_i = pos_i_temp
  15. elif sum_temp < 0:# 和小于0的子串不需要考虑
  16. sum_temp = 0
  17. pos_i_temp = i+1
  18. if sum_max < 0:
  19. print(0,seq[0],seq[-1])
  20. else:
  21. print(sum_max,seq[pos_i],seq[pos_j])
  22. if __name__ == '__main__':
  23. main()

谢谢观看!敬请指正!

参考博客:https://www.cnblogs.com/allzy/p/5162815.html

原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805514284679168

python编写PAT 1007 Maximum Subsequence Sum(暴力 分治法 动态规划)的更多相关文章

  1. PAT 1007 Maximum Subsequence Sum (25分)

    题目 Given a sequence of K integers { N​1​​ , N​2​​ , ..., N​K​​ }. A continuous subsequence is define ...

  2. 1007 Maximum Subsequence Sum (25分) 求最大连续区间和

    1007 Maximum Subsequence Sum (25分)   Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A ...

  3. 1007 Maximum Subsequence Sum (25 分)

    1007 Maximum Subsequence Sum (25 分)   Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A ...

  4. PAT 1007 Maximum Subsequence Sum(最长子段和)

    1007. Maximum Subsequence Sum (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Y ...

  5. PAT 1007 Maximum Subsequence Sum 最大连续子序列和

    Given a sequence of K integers { N1, N2, …, NK }. A continuous subsequence is defined to be { Ni, Ni ...

  6. PAT Advanced 1007 Maximum Subsequence Sum (25 分)

    Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to ...

  7. PAT 1007 Maximum Subsequence Sum (最大连续子序列之和)

    Given a sequence of K integers { N1, N2, ..., *N**K* }. A continuous subsequence is defined to be { ...

  8. 数据结构课后练习题(练习一)1007 Maximum Subsequence Sum (25 分)

    Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to ...

  9. [pat]1007 Maximum Subsequence Sum

    经典最大连续子序列,dp[0]=a[0],状态转移dp[i]=max(dp[i-1]+a[i],a[i])找到最大的dp[i]. 难点在于记录起点,这里同样利用动态规划s[i],如果dp[i]选择的是 ...

随机推荐

  1. Spring的控制反转(IOC)和依赖注入(DI)具体解释

    Spring的控制反转(IOC)和依赖注入(DI)具体解释 首先介绍下(IOC)控制反转: 所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的.这样控制器就有应 ...

  2. Html学习(三) 分类学习

    代码: <h1>这是一级分类吗</h1> <h2>这是二级分类吗</h2> <h3>这是三级分类吗 </h3> 效果: 介绍: ...

  3. bzoj4873: [Shoi2017]寿司餐厅(最大权闭合子图)

    4873: [Shoi2017]寿司餐厅 大难题啊啊!!! 题目:传送门 题解:一眼题是网络流,但还是不会OTZ,菜啊... %题解... 最大权闭合子图!!! 好的...开始花式建边: 1.对于每个 ...

  4. react ---- Router路由的使用和页面跳转

    React-Router的中文文档可以参照如下链接: http://react-guide.github.io/react-router-cn/docs/Introduction.html 首先,我们 ...

  5. java9新特性-10-语法改进:UnderScore(下划线)使用的限制

    1.使用说明 在java 8 中,标识符可以独立使用“_”来命名:   但是,在java 9 中规定“_”不再可以单独命名标识符了,如果使用,会报错:    

  6. 验证备份集-使用DBVERIFY工具

    DBVERIFY确认备份集是否存在坏块 验证TEST03.DBF 文件的是否存在坏块 C:\Documents and Settings\Administrator>dbv file=D:\or ...

  7. 在MAC上安装lxml到Python3

    首先可以直接使用以下命令安装lxml,但是会默认安装到Python2,没有找到怎么指定安装到Python3 sudo easy_install lxml 想要安装到Python3需要先安装pip: s ...

  8. WebKit载入流程 - 概述

    之前写了几篇载入流程的说明,是从下向上看,有点仅仅见树木不见森林的感觉.经过近期一段时间的学习,有了能加以概括抽象的方法. WebKit载入流程和页面组成是直接相关的,页面就是WebKit要载入的对象 ...

  9. 字符串匹配:KMP

    參考:从头到尾彻底理解KMP 在字符串 str 中 匹配模式串 pattern 1. 计算模式串的 next 数组: 2. 在字符串中匹配模式串:当一个字符匹配时,str[i++], pattern[ ...

  10. AFNetworking框架的使用

    #import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...