题解:P1001 A+B Problem

· · 题解

看见楼上楼下各路神仙对轰,小蒟蒻认为自己还是太弱了,不会什么太高深的算法,所以写个二维前缀和吧(主要是会的都被写完了)

我们来观察下面这张图:

通过输入数据构造如上的矩形,我们需要的答案就是红框部分矩形的值的和。这就是二维前缀和的模板题了。话不多说,上代码:

#include<bits/stdc++.h>
using namespace std;
using LL = long long;

const int N = 5;
LL a, b, sum[N][N], t[N][N];

inline LL read()
{
    LL w = 0, t = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9'){if(ch == '-')t = -1;ch = getchar();}
    while('0' <= ch && ch <= '9')w = w*10+(ch&15),ch = getchar();
    return w*t;
}

int main()
{
    a = read(), b = read();
    for(int i = 1; i <= 2; i++)
        for(int j = 1; j <= 2; j++)
        {
            if(i == 1)t[i][j] = a;
            else t[i][j] = b;
            sum[i][j] = sum[i-1][j]+sum[i][j-1] - sum[i-1][j-1] + t[i][j];
        }
    printf("%lld\n", sum[2][2]-sum[2][1]);

    return 0;
}