Cod sursa(job #1937748)

Utilizator raulrusu99Raul Rusu raulrusu99 Data 24 martie 2017 10:50:49
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.11 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("undo.in");
ofstream g("undo.out");
#define N_MAX 525
#define O_MAX 500005
long long aib[N_MAX][N_MAX];
///          pos        x    y
vector <pair<int, pair <int, int> > > Q[O_MAX];
///               nod  val        x    y
vector <pair<pair<int, int>, pair<int, int> > > G[O_MAX];
int s[O_MAX];
long long sol[O_MAX];
int n, m;

void update(int posx, int posy, int _val)
{
    long long x, y;
    for(x = posx; x <= n; x += x & (-x))
        for(y = posy; y <= n; y += y & (-y))
            aib[x][y] += _val;
}

long long query(int posx, int posy)
{
    long long sum = 0;
    long long x, y;
    for(x = posx; x > 0; x -= x & (-x))
        for(y = posy; y > 0; y -= y & (-y))
            sum += aib[x][y];
    return sum;
}

void addNode(int node, int tata, int i, int j, int _val)
{
    G[tata].push_back(make_pair(make_pair(node, _val), make_pair(i, j)));
}

void saveQuery(int node, int _pos, int i, int j)
{
    Q[node].push_back(make_pair(_pos, make_pair(i, j)));
}

void dfs(int nod)
{
    for(auto it:Q[nod])
        sol[it.first] = query(it.second.first, it.second.second);
    for(auto it:G[nod])
    {
        update(it.second.first, it.second.second, it.first.second);
        dfs(it.first.first);
        update(it.second.first, it.second.second, -it.first.second);
    }
}

int main()
{
    int p, node = 0, a, b, _val, posQuery = 0, undo, dim = 0;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> p;
        if(p == 1)
        {
            f >> a >> b >> _val;
            dim++;
            node++;
            s[dim] = node;
            addNode(node, s[dim - 1], a, b, _val);
        }
        if(p == 2)
        {
            f >> a >> b;
            posQuery++;
            saveQuery(s[dim], posQuery, a, b);
        }
        if(p == 3)
        {
            f >> undo;
            dim++;
            s[dim] = s[dim - undo - 1];
        }
    }
    dfs(0);
    for(int i = 1; i <= posQuery; i++)
        g << sol[i] << "\n";
    return 0;
}