Monday, January 7, 2019

[Spoj] MATSUM - Matrix Summation

Author            : Dipu Kumar Mohanto 
                    CSE, Batch - 6
                    BRUR.
Problem Statement : MATSUM - Matrix Summation
Source            : Spoj
Category          : Data Structure
Algorithm         : Binary Indexed Tree - 2D
Verdict           : Accepted
#include "bits/stdc++.h"
 
using namespace std;
 
#define ll             long long int
 
static const int maxn = 1024 + 5;
 
ll res[maxn][maxn];
ll data[maxn][maxn];
 
int row, col;
 
inline void update(int r, int c, ll val)
{
    for (int x = r; x <= row; x += (x & -x))
    {
        for (int y = c ; y <= col; y += (y & -y))
        {
            res[x][y] += val;
        }
    }
}
 
inline ll read(int r, int c, ll sum = 0)
{
    for (int x = r; x > 0; x -= (x & -x))
    {
        for (int y = c ; y > 0; y -= (y & -y))
        {
            sum += res[x][y];
        }
    }
    return sum;
}
 
 
int main()
{
    int tc;
    cin >> tc;
    for (int tcase = 1; tcase <= tc; tcase++)
    {
        int n;
        cin >> n;
        row = col = n;
        for (int i = 0; i <= row; i++)
        {
            for (int j = 0; j <= col; j++)
            {
                data[i][j] = 0;
                res[i][j] = 0;
            }
        }
        string type;
        while (cin >> type)
        {
            if (type[0] == 'E') break;
            if (type == "SET")
            {
                int x, y;
                ll val;
                cin >> x >> y >> val;
                x++, y++;
                ll add = val - data[x][y];
                data[x][y] = val;
                update(x, y, add);
            }
            else
            {
                int x1, y1, x2, y2;
                cin >> x1 >> y1 >> x2 >> y2;
                x1++, y1++;
                x2++, y2++;
                ll v1 = read(x2, y2);
                ll v2 = read(x2, y1-1);
                ll v3 = read(x1-1, y2);
                ll v4 = read(x1-1, y1-1);
                ll ans = v1 - v2 - v3 + v4;
                cout << ans << endl;
            }
        }
    }
}
 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.