Niu Ke Practice 63 C

l i n k link link

C 牛牛的揠苗助长

Title: Niuniu has a row of vegetable gardens, length n, iiThe height of the vegetables in the i piece of vegetable garden isa [i] a[i]a [ i ] . No.iii heaven,iiThe height of the i piece of vegetable garden will increase by 1, then + 1 n+1n+On a day, the height of the first vegetable garden increases by 1, and so on. But Niuniu has a kind of magic. It can increase or decrease the height of a vegetable garden by 1, and ask at least how many days it takes to make all vegetable gardens the same height. At the beginning of the problem guarantee, the height of the vegetable garden was uneven.
Idea: Dichotomy + median. Dichotomy can be used to convert the required question into a critical question, then how to judgexxIs x days okay? We know that we need to turn all heights into uniform heights. It has nothing to do with absolute heights, but with relative heights. Therefore, we first find out where the height of the vegetable garden has increased relatively, and then we get a new array, which we require It is at least how many days it takes to make all the elements of this array the same. If the value is less than x, it will work, otherwise it will not work. Making all the elements in the array the same is the problem that the median can solve. Then this question can be written.
code codecode

#include <bits/stdc++.h>
#define ll long long
#define pi pair<int,int>
#define mk make_pair
#define pb push_back
using namespace std;

const int maxn = 1e5+10;
int a[maxn];
int n;

bool ok(ll x)
{
    
    
	vector<ll>G;
	for(int i=1;i<=n;i++)G.pb(a[i] + (i <= x%n));
	sort(G.begin(),G.end());
	
	ll m = G[n/2],ans = 0;
	
	for(auto it : G)
	{
    
    
		ans += abs(it - m);
	}
	if(ans <= x)return true;
	else return false;
}
int main()
{
    
    
	
	cin >> n;
	for(int i=1;i<=n;i++)scanf("%d",a+i);
	ll l = 1,r = 1e14,ans = 0;

	while(l <= r)
	{
    
    
		int mid = (l+r)/2;
		if(ok(mid))r = mid - 1,ans = mid;
		else l = mid + 1;
	}
	printf("%lld\n",ans);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44499508/article/details/106731913