CSU-1023修路(二分)

版权声明:仅供研究,转载请注明出处。 https://blog.csdn.net/CSUstudent007/article/details/82118967

 要求最短时间,那么直接二分时间。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 305;
const int mt= 300*1000+5;
int p[maxn];
bool judge(int m,int n,int t){
	int sum=0;
	int cn=1;
	for(int i=0;i<m;i++)
	{
		if(p[i]>t) return 0;
		if(p[i]+sum<=t){
			sum+=p[i];
		}
		else{
			sum=p[i];
			cn++;
		}
	}
	if(cn<=n) return 1;
	else return 0;
}
int bsearch(int m,int n){
	int left=0,right=mt;
	int mid,ans=mt;
	while(left<=right)
	{
		mid=(right-left)/2+left;
		if(judge(m,n,mid))
		{
			ans=min(ans,mid);
			right=mid-1;
		}
		else{
			left=mid+1;
		}
	}
	return ans;
}
int main()
{
	int T,m,n;
	cin>>T;
	while(T--)
	{
		cin>>m>>n;
		memset(p,0,sizeof(p));
		for(int i=0;i<m;i++)
		{
			cin>>p[i];
		}
		cout<<bsearch(m,n)<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CSUstudent007/article/details/82118967