Cod sursa(job #1494860)

Utilizator alexpetrescuAlexandru Petrescu alexpetrescu Data 1 octombrie 2015 22:14:44
Problema Partitie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.87 kb
#include <cstdio>
#include <algorithm>
#include <cctype>
#define BUF_SIZE 4096
#define MAXN 300000
typedef struct{
    int v, t;
}mycreation;
mycreation e[MAXN], v[MAXN];
int r[MAXN], h, pos=BUF_SIZE;
char buf[BUF_SIZE];
FILE *fin;
inline char nextch(){
    if(pos==BUF_SIZE){
        fread(buf, BUF_SIZE, 1, fin);
        pos=0;
    }
    return buf[pos++];
}
inline int read(){
    int x=0;
    char ch=nextch();
    while(!isdigit(ch)){
        ch=nextch();
    }
    while(isdigit(ch)){
        x=10*x+ch-'0';
        ch=nextch();
    }
    return x;
}
bool cmp(const mycreation a, const mycreation b){
    return a.v<b.v;
}
inline int fiust(int p){
    return 2*p+1;
}
inline int fiudr(int p){
    return 2*p+2;
}
inline void swap(int x, int y){
    mycreation aux=e[x];
    e[x]=e[y];
    e[y]=aux;
}
inline void coborare(int p){
    int q, f=1;
    while((f==1)&&(fiust(p)<h)){
        q=fiust(p);
        if((fiudr(p)<h)&&(e[fiudr(p)].v<e[q].v)){
            q=fiudr(p);
        }
        if(e[q].v<e[p].v){
            swap(p, q);
            p=q;
        }else{
            f=0;
        }
    }
}
int main(){
    int n, i, k;
    FILE *fout;
    fin=fopen("partitie.in", "r");
    fout=fopen("partitie.out", "w");
    n=read();
    k=read();
    for(i=0; i<n; i++){
        v[i].v=read();
        v[i].t=i;
    }
    std::sort(v, v+n, cmp);
    h=1;
    e[0].v=v[0].v;
    e[0].t=1;
    r[v[0].t]=1;
    for(i=1; i<n; i++){
        if(v[i].v-e[0].v<k){
            e[h].v=v[i].v;
            h++;
            e[h-1].t=h;
            r[v[i].t]=h;
        }else{
            r[v[i].t]=e[0].t;
            e[0].v=v[i].v;
            coborare(0);
        }
    }
    fprintf(fout, "%d\n", h);
    for(i=0; i<n; i++){
        fprintf(fout, "%d\n", r[i]);
    }
    fclose(fin);
    fclose(fout);
    return 0;
}