SPOJ #453. Sums in a Triangle (tutorial)

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.

#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

 

转载于:https://www.cnblogs.com/tonix/p/3541392.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值