Cod sursa(job #1865945)

Utilizator l-teenLucian l-teen Data 2 februarie 2017 12:50:23
Problema Ghiozdan Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.61 kb
// Gh2.cpp : Defines the entry point for the console application.
//

#define MAXSTEP 200
#define ARRSIZE (MAXSTEP + 1)

#include <stdio.h>


int ghiozdan()
{
    FILE *in, *out;
    int i, j, weight, noInputs, inputs[ARRSIZE], steps[ARRSIZE], history[ARRSIZE][ARRSIZE], position = 0, maxweight = 0, foundGreaterValue;

    if (!(in = fopen("ghiozdan.in", "r")))
        return -1;

    if (!fscanf(in, "%d %d", &noInputs, &weight))
        return -1;

    for (i = 0; i < ARRSIZE; ++i)
    {
        inputs[i] = 0;
        steps[i] = 0;
        for (j = 0; j < ARRSIZE; ++j)
            history[i][j] = 0;
    }

    for (i = 0; i < noInputs; ++i)
    {
        if (!fscanf(in, "%d", &j))
            return -1;
        if ((j<1) || (j>MAXSTEP))
            return -1;
        ++inputs[j];
    }

    for (i = 0; (i < ARRSIZE) && (i<=weight); ++i)
    {
        if (inputs[i])
        {
            ++steps[i];
            for (j = 0; j < ARRSIZE; ++j)
                history[i][j] = inputs[j];
            --history[i][i];
            maxweight = i;
        }
    }

    for (position = 0; position < weight;++position)
    {
        if (steps[position%ARRSIZE])
        {
            foundGreaterValue = 0;
            for (i = 1; i < ARRSIZE; ++i)
            {
                if ((history[position%ARRSIZE][i]) && (position + i <= weight))
                {
                    if ((steps[(position + i) % ARRSIZE] > steps[position%ARRSIZE] + 1) || (steps[(position + i) % ARRSIZE] == 0))
                    {
                        steps[(position + i) % ARRSIZE] = steps[position%ARRSIZE] + 1;
                        for (j = 0; j < ARRSIZE; ++j)
                            history[(position + i) % ARRSIZE][j] = history[position%ARRSIZE][j];
                        --history[(position + i) % ARRSIZE][i];
                        
                        if (maxweight < position + i)
                            maxweight = position + i;
                    }
                    foundGreaterValue = 1;
                }

            }
            if (foundGreaterValue)
                steps[position%ARRSIZE] = 0;
        }
    }

    if (!(out = fopen("ghiozdan.out", "w")))
        return -1;

    if (!fprintf(out, "%d %d", maxweight, steps[maxweight%ARRSIZE]))
        return -1;

    for (i = 0; i < ARRSIZE; ++i)
        for (j = 0; j < inputs[i] - history[maxweight%ARRSIZE][i]; ++j)
            if (!fprintf(out, "\n%d", i))
                return -1;

    (void)fclose(in);
    (void)fclose(out);

    return 0;
}

int main()
{
	return ghiozdan();
}