Cod sursa(job #1489588)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 21 septembrie 2015 18:09:31
Problema Partitie Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.82 kb
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;

ifstream in("partitie.in");
ofstream out("partitie.out");

const int MAX_N = 300000;

struct Element {
    int val;
    int ind;
};

struct Group {
    int th;
    int ind;
} gAux;

int nHeap;
Group H[MAX_N + 1];

void upHeap(int pos) {
    int initPos = pos;
    while(pos > 1 && H[pos/2].th > H[initPos].th) {
        H[pos] = H[pos/2];
        pos /= 2;
    }
    swap(H[initPos], H[pos]);
}

void downHeap(int pos) {
    int son;
    do {
        son = 0;
        if(2*pos <= nHeap && H[pos].th > H[pos*2].th) son = 2*pos;
        if(2*pos + 1 <= nHeap && H[son].th > H[2*pos+1].th) son = 2*pos + 1;
        if(son) {
            swap(H[pos], H[son]);
            pos = son;
        }
    } while(son);
}

void insHeap(Group E) {
    H[++nHeap] = E;
    upHeap(nHeap);
}

void delHeap(int pos) {
    H[pos] = H[nHeap--];
    if(pos > 1 && H[pos].th < H[pos/2].th) upHeap(pos);
    else downHeap(pos);
}

bool elSort(Element A, Element B) {
    return A.val < B.val;
}

Element V[MAX_N + 1];
int Sol[MAX_N + 1];

int main() {
    int n, d, i, th;

    in >> n >> d;
    for(i = 1; i <= n; i++) {
        in >> V[i].val;
        V[i].ind = i;
    }
    sort(V+1, V+n+1, elSort);

    insHeap({V[1].val + d, 1});
    Sol[V[1].ind] = 1;

    for(i = 2; i <= n; i++) {
        gAux = H[1];
        if(V[i].val < gAux.th) {
            insHeap({V[i].val + d, nHeap + 1});
            Sol[V[i].ind] = nHeap;
        }
        else {
            delHeap(1);
            Sol[V[i].ind] = gAux.ind;
            insHeap({V[i].val + d, gAux.ind});
        }
    }

    out << nHeap << "\n";
    for(i = 1; i <= n; i++) {
        out << Sol[i] << '\n';
    }

    return 0;
}