二分查找之月度开销

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool IsValid(vector<int> vecdays,int M,int fajomax)
{
	int cnt = 0, sum = 0;
    for (int i = 0; i < vecdays.size(); i++)
    {
        if (sum + vecdays[i] > fajomax)
		{
			cnt++;
			sum = vecdays[i];
		}
        else
            sum += vecdays[i];
    }
    return cnt >= M;
	//int sum=0,iret=0;
	//for(int i=0;i<vecdays.size();i++)
	//{
		//if((sum+vecdays[i])<=fajomax)
		//{
			//sum+=vecdays[i];
		//}
		//else
		//{
		//	iret++;
		//	sum=vecdays[i];
		//}
		//if(i==(vecdays.size()-1))
		//{
		//	iret++;
		//	break;
		//}
	//}
	//return iret>=M;
}
 
int main()
{
	int N=0,M=0;
	cin>>N>>M;
	int icakenum=N;
	vector<int> veccakev;
	vector<int> veccakev2;
	while((icakenum--)>0)
	{
		int r=0;
		cin>>r;
		veccakev.push_back(r);
		veccakev2.push_back(r);
	}
 
	//二分法
	int imin=0,imax=0;
	for(int i=0;i<veccakev.size();i++)
	{
		imax+=veccakev[i];
	}
	//imin=imax/N;
	sort(veccakev2.begin(),veccakev2.end());
	imin=veccakev2[veccakev2.size()-1];
	int ivalue=0;//(imax+imin)/2;
	while((imax-imin)>=0)
	{
		ivalue=imin+(imax-imin)/2;
		bool blret=IsValid(veccakev,M,ivalue);
		if(blret)
		{
			imin=imin+(imax-imin)/2+1;
		}
		else
		{
			imax=imin+(imax-imin)/2-1;
		}
		//ivalue=(imax+imin)/2;
	}
	printf("%d\n",(imin));
 
	return 0;
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页