Cod sursa(job #3218167)

Utilizator Mirc100Mircea Octavian Mirc100 Data 26 martie 2024 12:24:54
Problema Interclasari Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.29 kb
/*
 *
3
6
0 7 8 11 12 15
0
2
6 12
 */
#include<iostream>
#include<fstream>
const int MAXDIM=21;
using namespace std;
int* foto[21];
int parent(int i) {
    if(i==0)
        return 0;
    return (i-1)/2; }

int left(int i) { return (2*i + 1); }

int right(int i) { return (2*i + 2); }
void upKey(pair<int,int> h[MAXDIM], int &dim_heap, int i ){
    while (i != 0 && foto[h[parent(i)].first][h[parent(i)].second] > foto[h[i].first][h[i].second])
    {
        swap( h[i],  h[parent(i)]);
        i = parent(i);

    }
}
void insert(pair<int,int> h[MAXDIM], int &dim_heap, pair<int,int> x){
    if (dim_heap >= MAXDIM)
        return;
    h[dim_heap]=x;
    int i=dim_heap;
    dim_heap++;
    upKey(h,dim_heap,i);

}
void downKey (pair<int,int> h[MAXDIM], int dim_heap, int i) {
    //fiul minim
    while (left(i) < dim_heap) {
        int min_desc = left(i);
        int r = right(i);

        if (r < dim_heap && foto[h[r].first][h[r].second] < foto[h[min_desc].first][h[min_desc].second])
            min_desc = r;
        swap(h[i], h[min_desc]);
        i = min_desc;
    }
}
pair<int,int> extractMin(pair<int,int> h[MAXDIM], int &dim_heap){
    if (dim_heap==0)
        return {-1,-1};
    pair<int,int> x=h[0];
    h[0] = h[dim_heap-1];
    dim_heap--;
    downKey(h,dim_heap,0);
    return x;
}

void print(pair<int,int> h[MAXDIM],  int dim_heap){
    for(int i=0;i<dim_heap;i++)
        cout<<foto[h[i].first][h[i].second]<<" ";
    cout<<endl;
}

int main(){
    ifstream f("interclasari.in");
    ofstream g("interclasari.out");
    int k, n[21], ind[21];
    int nr=0;
    f  >>k;


    for(int i=0;i<k;i++){
        f>>n[i];
        nr+=n[i];

        foto[i]=new int[n[i]];
        for(int j=0;j<n[i];j++)
            f>>foto[i][j];
    }
    f.close();
    g<<nr<<endl;

    pair<int,int> h[21]; //in heap - pozitie (indice sir, indice element)
    int dim_h=0;
    for(int i=0;i<k;i++){
        if (n[i]>0)
            insert(h,dim_h,{i,0});
        //print(h,dim_h );
    }
    while(dim_h>0){
        pair<int,int> x=extractMin(h,dim_h);
        g<<foto[x.first][x.second]<<" ";
        if (x.second<n[x.first]-1){
            insert(h,dim_h,{x.first,x.second+1});
        }
        //print(h,dim_h );
    }

g.close();

}