Codeforces Round #763 (Div. 2) C. Balanced Stone Heaps

题目链接:Problem - C - Codeforces

题目描述:

Codeforces Round #763 (Div. 2) C. Balanced Stone Heaps_第1张图片

输入描述:

Codeforces Round #763 (Div. 2) C. Balanced Stone Heaps_第2张图片 

输出描述:

 

样例及解释:

Codeforces Round #763 (Div. 2) C. Balanced Stone Heaps_第3张图片 

 题意:有n个石头堆,从第三堆开始到第n堆可以选择3d个石头,把2d个给i-2堆,d个给i-1堆,问最大情况的最小堆

思路:满足条件的最小堆的值一定在这些石头的最小值和最大值之间,我们二分这个区间进行查找,如果这个值可以满足就去后面找,不行就去前面找

题目要求石头必须从前往后遍历,相当于从后往前,如果后面提供的石头数量 >= 最小值,那么这堆石头都可以往前面扔

#include
using namespace std;
#define endl "\n"
#define IOS ios::sync_with_stdio(false)
int arr[200005];
int b[200005];
int c[200005];
int n;
bool check(int mid){
	for(int i = 1; i <= n; i++){
		b[i] = 0;
		c[i] = arr[i];
	}
	for(int i = n; i >= 3; i--){
		if(c[i] + b[i] >= mid){
			if(b[i] >= mid){
				int ans = c[i] / 3;
				c[i] -= ans * 3;
				b[i - 2] += ans * 2;
				b[i - 1] += ans;
			}else{
				int ans = (c[i] + b[i] - mid) / 3;
				c[i] -= ans * 3;
				b[i - 2] += ans * 2;
				b[i - 1] += ans;
			}
		}
	}
	int minn = 2e9;
	for(int i = 1; i <= n; i++){
		minn = min(c[i] + b[i], minn);
	}
	if(minn >= mid){
		return true;
	}
	return false;
}
int main(){
	IOS;
	int t;
	cin >> t;
	while(t--){
		
		cin >> n;
		int minn = 2e9;
		int maxn = 0;
		for(int i = 1; i <= n; i++){
			cin >> arr[i];
			minn = min(arr[i], minn);
			maxn = max(maxn, arr[i]);
		}
		while(minn <= maxn){
			int mid = (minn + maxn) / 2;
			if(check(mid)){
				minn = mid + 1;
			}else{
				maxn = mid - 1;
			}
		}
		cout << maxn << endl;
		
	}
	return 0;
}

你可能感兴趣的:(c++,思路,二分查找,算法)