What is the best time complexity approach for the problem?
I've somehow managed to get AC with a very slow DP O(n^3) solution.
How is it possible to improve the algorithm?
Is there any greedy approach?
Moderator: Board moderators
#include<iostream>
using namespace std;
#define FOR(i,n) for(int i=0;i<n;++i)
int in[1024],n,m;
bool f(int S){
int C=0;
int s=0;
FOR(i,n){
if(s+in[i]>S )s=in[i],C++;
else s+=in[i];
}
C++;
if(C<=m)return true;
else return false;
}
int main(){
//freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&m)>0 ){
FOR(i,n)scanf("%d",&in[i] );
int Sum=0;
FOR(i,n)Sum+=in[i];
int l=2147483647,r=Sum+1;
FOR(i,n)l=min(l,in[i] );
while(l<r){
int mid=(r+l)/2;
if( f(mid)==true )r=mid;
else l=mid+1;
}
printf("%d\n",l);
}
return 0;
}5
1 2 3 5 4
2 3
12 3
2 3
3 12
5 4
1 2 3 5 4
3 100
4 78 9
12
12
5
82
#include <cstdio>
#include <cstring>
#define MAX 5000005
#define min(a,b) a < b ? a : b
int order[MAX];
int cek (int m, int v, int c)
{
int sum = 0;
for (int i = 0; i < v; i ++)
{
if ((sum + order[i]) <= m)
{
sum += order[i];
}else
{
c--, sum = 0, i --;
if (c == 0 || order[i] > m) return 0;
}
}
return 1;
}
void in_o ()
{
int ves, con;
while (scanf ("%d %d", &ves, &con) == 2)
{
int sum = 0, ans = 1 << 25;
for (int i = 0; i < ves; i++)
{
scanf ("%d", &order[i]);
sum += order[i];
}
int l = 1, r = sum;
while (l <= r)
{
int m = (l + r) / 2, x = cek (m, ves, con);
if (x)
{
ans = min (ans, m);
r = m - 1;
}else
{
l = m + 1;
}
}
printf ("%d\n", ans);
}
}
int main ()
{
in_o ();
return 0;
}
Whenever milk from a vessel is poured into a container, the milk in the vessel must be completely poured into that container only. That is milk from same vessel can not be poured into different containers.
(1 <= m <= 1000000)
The ith container must be filled with milk only from those vessels that appear earlier to those that fill jth container, for all i < j
3 100
4 78 9
Users browsing this forum: No registered users and 1 guest