Cod sursa(job #1988722)

Utilizator mariusn01Marius Nicoli mariusn01 Data 4 iunie 2017 14:14:47
Problema Reconst Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.75 kb
#include <fstream>
#include <algorithm>
#define DIM 2010

using namespace std;
struct nod {
    int st;
    int dr;
    int cost;
    nod *next;
};
nod v[DIM];
int a[DIM];
int n, m, i, j, ST, DR, COST, nextST, nextDR, nextCOST;
nod *p, *q, *u, *r;

void loadInf(nod *p, int i) {
    p->st = v[i].st;
    p->dr = v[i].dr;
    p->cost = v[i].cost;
}

void loadInf(nod *p, int st, int dr, int cost) {
    p->st = st;
    p->dr = dr;
    p->cost = cost;
}

int cmp(nod a, nod b) {
    if (a.st == b.st)
        return a.dr <= b.dr;
    else
        return a.st <= b.st;
}

int main () {
    ifstream fin ("reconst.in");
    ofstream fout("reconst.out");

    fin>>n>>m;
    for (i=1;i<=m;i++) {
        fin>>v[i].st>>v[i].dr>>v[i].cost;
        if (v[i].st > v[i].dr) {
            swap(v[i].st, v[i].dr);
        }
    }

    sort(v+1, v+m+1, cmp);

    p = new nod;
    loadInf(p, m);
    p->next = NULL;
    u = p;

    for (i=m-1;i>=1;i--) {
        if (v[i].st != p->st) {
            q = new nod;
            loadInf(q, i);
            q->next = p;
            p = q;
            continue;
        }
        ST = v[i].st;
        DR = v[i].dr;
        COST = v[i].cost;
        q = p;
        for (;;) {
            while (q!= NULL && ST > q->st )
                q = q->next;
            if (q == NULL) {
                u->next = new nod;
                u = u->next;
                u->next = NULL;
                loadInf(u, ST, DR, COST);
                break;
            }

            if (ST == q->st) {
                if (DR == q->dr)
                    break;
                if (DR < q->dr) {
                    nextST = DR+1;
                    nextDR = q->dr;
                    nextCOST = q->cost - COST;

                    q->dr = DR;
                    q->cost = COST;

                    ST = nextST;
                    DR = nextDR;
                    COST = nextCOST;

                } else {
                    ST = q->dr+1;
                    COST = COST - q->cost;
                }
            } else {
                r = new nod;
                loadInf(r, ST, DR, COST);
                r->next = q->next;
                q->next = r;
                if (r->next == NULL)
                    u = r;
                break;
            }

        }

    }

    m = 0;
    q = p;
    while (q) {
        m++;
        v[m].st = q->st;
        v[m].dr = q->dr;
        v[m].cost = q->cost;
        q = q->next;
    }

    for (i=m;i>=1;i--) {
        int suma = 0;
        for (j=v[i].st;j<=v[i].dr;j++)
            suma += a[j];
        a[ v[i].st ] += (v[i].cost - suma);
    }

    for (i=1;i<=n;i++)
        fout<<a[i]<<" ";

    return 0;
}