Cod sursa(job #2805920)

Utilizator dfettiDaniel Fetti dfetti Data 22 noiembrie 2021 09:27:00
Problema Transport Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.91 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("transport.in");
ofstream fout("transport.out");

int n, k;
int a[16001];

int check(int c)
{
	int aux = 0;
	int t = 1;

	for (int i = 0; i < n; ++i)
	{
		if (c < a[i])
			return -1;

		if (aux + a[i] <= c)
		{
			aux += a[i];
		}
		else
		{
			t++;
			aux = a[i];
		}
	}

	return t;
}

int main()
{
	fin >> n >> k;
	for (int i = 0; i < n; ++i)
		fin >> a[i];

	int c = 0;
	for (int i = 0; i < n; ++i)
		c += a[i];

	int t = 1;
	int lo = 1;
	int hi = c;
	int mid = 0;

	while (t != k)
	{
		//cout << "lo: " << lo << " hi: " << hi << endl;
		mid = (lo + hi) / 2;

		t = check(mid);
		//cout << "MID: " << mid << " t: " << t << endl;

		if (t == -1)
		{
			lo = mid + 1;
			continue;
		}

		if (t < k)
		{
			hi = mid;
		}
		else
		{
			lo = mid;
		}
	}

	fout << lo;

	return 0;
}