Cod sursa(job #2122834)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 5 februarie 2018 15:55:45
Problema Ghiozdan Scor 90
Compilator cpp Status done
Runda Simulare 45 Marime 2.73 kb
#include <fstream>
#include <algorithm>
#include <set>

using namespace std;

ofstream fout ("ghiozdan.out");

class InputReader {
	public:
        InputReader() {}
        InputReader(const char *name) {
            fin = fopen(name, "r");
			buffpos = Size - 1;
        }
        inline InputReader &operator >>(int &n) {
			char ch = nextpos();
            while(ch < '0' || ch > '9') {
                ch = nextpos();
            }

            n = 0;
            while('0' <= ch && ch <= '9') {
                n = n * 10 + ch - '0';
                ch = nextpos();
            }
            return *this;
        }
    private:
        FILE *fin;
        static const int Size = 1 << 17;
        int buffpos;
        char buff[Size];

        inline char nextpos() {
            ++ buffpos;
            if(buffpos == Size) {
                buffpos = 0;
                fread(buff, Size, 1, fin);
            }
			return buff[ buffpos ];
        }
} fin ("ghiozdan.in");

const int gmax = 75e4 + 2;
const int nmax = 2e4;
const int inf = 1 << 30;

struct str {
    int nrmin;
    unsigned char pun;

    str () {
        nrmin = inf;
    }
} d[gmax + 1];

struct lst {
    int nxt_ind, val;

    lst () {}
    lst (int _nxt_ind, int _val) {
        nxt_ind = _nxt_ind, val = _val;
    }
} l[gmax + 1];

int v[nmax + 1];
int unde[gmax + 1];
int sz;
set< int > s;

void baga (int val) {
    int ant = *s.lower_bound( val );
    s.insert( val );

    int u = unde[ ant ];
    ++ sz;
    unde[ val ] = sz;

    l[ sz ].val = val;
    l[ sz ].nxt_ind = l[ u ].nxt_ind;
    l[ u ].nxt_ind = sz;
}

void reconst (int x) {
    fout << x << " " << d[ x ].nrmin << "\n";

    while (x != 0) {
        fout << (int)d[ x ].pun << "\n";
        x -= d[ x ].pun;
    }
}

bool cmp (int a, int b) {
    return a > b;
}

int main () {
    int n, k;
    fin >> n >> k;

    s.insert(k + 1);
    l[ 0 ] = lst(1, k + 1);
    unde[k + 1] = 0;

    l[ 1 ] = lst(1, -1);
    sz = 1;

    d[ 0 ].nrmin = d[ 0 ].pun = 0;
    baga( 0 );

    for (int i = 1; i <= n; ++ i) {
        fin >> v[ i ];
    }

    sort(v + 1, v + n + 1, cmp);
    for (int i = 1; i <= n; ++ i) {
        int x = v[ i ];

        int j = l[ 0 ].nxt_ind;
        while (l[ j ].val != -1) {
            int y = l[ j ].val + x;

            if (y <= k) {
                if (d[ y ].nrmin == inf) {
                    baga( y );
                }
                if (d[ y ].nrmin > d[y - x].nrmin + 1) {
                    d[ y ].nrmin = d[y - x].nrmin + 1;
                    d[ y ].pun = x;
                }
            }

            j = l[ j ].nxt_ind;
        }
    }

    for (int i = k; i >= 0; -- i) {
        if (d[ i ].nrmin != inf) {
            reconst( i );
            break;
        }
    }

    fout.close();
    return 0;
}