SPOJ #453. Sums in a Triangle (tutorial)
2014-02-09 13:37
351 查看
It is a small fun problem to solve. Since only a max sum is required (no need to print path), we can only keep track of the max value at each line. Basically it is still a human labor simulation work. To be more specifically, we need keep track of a line of max sums.
But there are 1000*100 input, so special optimization is required. The naive solution would copy data between 2 arrays, and actually that's not necessary. Logically, we only have 2 arrays - result array and working array. After one line is processed, working array can be result array for next line, so we can only switch pointers to these 2 arrays, to avoid expensive memory copy.
View Code
But there are 1000*100 input, so special optimization is required. The naive solution would copy data between 2 arrays, and actually that's not necessary. Logically, we only have 2 arrays - result array and working array. After one line is processed, working array can be result array for next line, so we can only switch pointers to these 2 arrays, to avoid expensive memory copy.
#include <iostream> #include <cstdio> #include <cstdlib> using namespace std; int aret[100] = {0}; int atmp[100] = {0}; int proc_line(int r, int *aret, int *atmp) { if(r == 1) { int in = 0; cin >>in; aret[0] = in; atmp[0] = in; return in; } // Get current line and calc int rmax = -1; for(int i = 0; i < r; i ++) { int tmp = 0; scanf("%d", &tmp); int prevInx = i == 0 ? 0 : i - 1; int prevVal = aret[prevInx]; int currMax = (i + 1) == r ? tmp + prevVal : max(tmp + aret[i], tmp + prevVal); atmp[i] = currMax; rmax = currMax > rmax ? currMax :rmax; } return rmax; } int main() { int runcnt = 0; cin >> runcnt; while(runcnt --) { int rcnt = 0; cin >> rcnt; int ret = 0; for(int i = 1; i <= rcnt; i ++) { bool evenCase = i % 2 == 0; ret = proc_line(i, !evenCase? aret:atmp, !evenCase?atmp:aret); } cout << ret << endl; } return 0; }
View Code
相关文章推荐
- android edittext设置软键盘按钮事件
- 天才与锻炼
- Android导入一个工程时提示 Invalid project description
- 2014年开年所思所想所做
- IPA反编译
- 基于AWS的自动化部署实践
- 微信公众平台开发解惑
- word break ii; trying - complete - no ac
- 读《你的灯亮着吗》小结
- Eclipse中查看jar包中的源码
- mysql更改timeouts数据库连接时间
- bash 快捷键
- (MBTI第一步)分析报告
- 转帖:DSG变速箱各类故障的简单解读,看了你就知道为什么会有问题了
- 数据仓库的定义
- Devexpress GridView 合计 与 格式化
- C++ is_partitioned
- tcp/ip协议学习笔记(6)广播与组播
- gridview主从表过滤时出现:不能启用此约束,因为不是所有的值都具有相应的父值的解决方法
- http协议详解