1044. Shopping in Mars (25)

考察二分

#include<iostream>
#include<vector>

void FindBest(std::vector<int>& sum, int m, int i, int& j, int& tmpSum)
{
	//j = tmpSum = -1;
	//binary search
	int l = i;
	int r = (int)sum.size()-1;
	//int all = sum[l]-sum[r];
	//important binary search
	while(l < r)
	{
		int mid = (l+r)/2;
		if(sum[mid]-sum[i-1] >= m)//let the answer set to r
			r = mid;
		else l = mid+1;//mid can not be the answer, so l = mid+1
	}
	j = r;
	tmpSum = sum[j]-sum[i-1];
}
int main()
{
	int n, m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		std::vector<int> sum;
		sum.assign(n+1, 0);
		for(int i = 1; i <= n; ++i)
		{
			scanf("%d",&sum[i]);
			sum[i] = sum[i-1]+sum[i];
		}
		//find solution
		std::vector<std::pair<int,int>> so;
		int best = -1;
		for(int i = 1; i <= n; ++i)
		{
			int j, tmpSum;
			FindBest(sum, m, i, j, tmpSum);//get j and tmpSum
			
			if(best == -1 || (tmpSum < best && tmpSum >= m))
			{
				best = tmpSum;
				so.clear();
				so.push_back(std::make_pair(i,j));
			}
			else if(best != -1 && tmpSum == best)
			{
				so.push_back(std::make_pair(i,j));
			}
		}
		//output
		for(int i = 0; i < so.size(); ++i)
			printf("%d-%d\n",so[i].first, so[i].second);
	}
	return 0;
}


 

你可能感兴趣的:(pat,ZJU)