高中的时候曾经看过同窗拿这本书做参考。当时翻阅的时候第一反应是本身确定看不下去,第二反应是内容太多了对于OI应该性价比不是很高。ios
固然,此书意义非凡,不是OI能衡量的,如今刚刚放假,因而计划有目的地通读,固然第一遍阅读,目标主要是掌握要点,深度方面必然还须要以后补漏,这里仅记录在阅读中本身较为有价值的思考。算法
给出一个序列表明天天的猪肉价格,咱们能够选择在某天买入而后在以后某天卖出,求最大收益。数组
而经典的最大子段和问题是,在序列中选取一段连续子序列的和,求这个最大和。
spa
在读算法导论以前我没有将这两个问题联系到一块儿,尽管问题简单,可是这一点也要想到:两问题本质是同样的。将最大子段和问题中的序列求一遍前缀和,以后原问题就转化为了在前缀和数组上的猪肉问题。
code
转化后重作水题:luogu1115 最大字段和get
代码:string
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; int n; int main () { scanf("%d", &n); long long minn = 0;//前缀和最小值 long long su = 0; //前缀和变量 long long ans = -9999999999; //答案 for (int i = 1; i <= n; i++) { long long xx; scanf("%lld", &xx); ans = max(ans, xx); su += xx; if (minn > su) { minn = su; } else { ans = max(ans, su - minn); } } printf("%d\n", ans); return 0; }
继续扩展水题:NOIP2013/2018 积木大赛
it
转化后重作水题:NOIP2013/2018 积木大赛io
代码:class
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int n; long long x, y, co = 0; int main() { scanf("%d", &n); scanf("%lld", &x); co = x; for (int i = 1; i < n; i++) { scanf("%lld", &y); if (y > x)//x为sum[i - 1],y为sum[i] y - x也就是还原a[i] { co += y - x; } x = y; } printf("%lld", co); return 0; }