Cod sursa(job #1691380)

Utilizator numedeutilizatorDaniel Meszaros numedeutilizator Data 18 aprilie 2016 10:25:14
Problema Transport Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.33 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("transport.in");
ofstream g("transport.out");

unsigned n, k, volume[16001], i, vol_max, lt, rt, mid, vol_sum, target, cap[16001], found;


unsigned check_cap(unsigned capacity)
{
    unsigned curLoad = 0, j = 1, m = 0, totalLoad = 0;
    for(m = 1; m <= k; m++)
    {
        curLoad = 0;
        while(curLoad <= capacity && j <= n)
        {
            if(curLoad+volume[j] > capacity)
                break;
            curLoad += volume[j];
            totalLoad += volume[j];
            //cout << volume[j] << endl;
            j++;
            //cout << curLoad << endl;
        }
        //cout << "total=" << totalLoad << endl;
        if(totalLoad == vol_sum)
            break;
    }
    /*while(m <= k)
    {
        if(curLoad == capacity)
        {
            cout << 1 << endl;
            if(m < k)
            {
                curLoad = 0;
                m++;
            }
            else
                break;
        }
        if(curLoad+volume[j] > capacity)
        {
            cout << 2 << endl;
            if(m < k)
            {
                curLoad = 0;
                m++;

            }
            else
                break;
        }
        curLoad += volume[j];
        totalLoad += curLoad;
        j++;
    }*/
    if(totalLoad < vol_sum)
        return 0;
    else if(totalLoad == vol_sum && m == k)
        return 1;
    else if(totalLoad == vol_sum && m < k)
        return 2;
}

int main()
{
    f >> n >> k;
    for(i = 1; i <= n; i++)
    {
        f >> volume[i];
        if(volume[i] > vol_max)
            vol_max = volume[i];
        vol_sum += volume[i];
    }
    lt = 0;
    for(i = vol_max; i <= vol_sum; i++)
    {
        lt++;
        cap[lt] = i;
    }
    rt = lt;
    lt = 1;
    //cout << check_cap(7);
    while(lt <= rt)
    {
        mid = lt + (rt-lt)/2;
        if(check_cap(cap[mid]) == 1)
        {
            found = 1;
            while(check_cap(cap[mid-1]) == 1)
                mid--;
            break;
        }
        else if(check_cap(cap[mid]) == 0)
            lt = mid+1;
        else if(check_cap(cap[mid]) == 2)
            rt = mid-1;
    }
    if(!found)
        g << -1;
    else
        g << cap[mid];

}