描述
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time .
Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.
输入
There are multiple cases.
For each case, the first line is an integer n, the second line has n integers indicating the number of dresses in each washing machine.
The range of n is [1, 10000].
The range of dresses number in a super washing machine is [0, 1e5]
输出
For each case, output one integer indicating the minimum number of moves, or -1 if impossible.
样例输入
3
1 0 5
3
0 3 0
3
0 2 0
样例输出
3
2
-1
题意
大概就是有一排洗衣机,里面有0~1e5件衣服不等,通过ans次移动,使每个洗衣机内衣服数量相同,如果始终无法达到要求,则输出-1,可以达到则输出最小移动次数。
移动规则:一次可以使一台或多台洗衣机往左或右边(相邻)转移一件衣服
思路
一开始在欢乐的英文单词中 好不容易读懂题意,然后发现自己应该也只能读懂题意了🌹
只需要考虑每一个点和它左边右边(直接把左右两边看成点)的状态即可,就是该点左边到达平均数需要几件衣服,右同。L=(i-1)*ave-sum[i-1],R类似。(sum是前缀和
)若都小于0,则表示左右两边都缺衣服,需要该点供给,此时的答案为abs(L)+abs(R),(因为一次一个点只能给一件,所以是和)其他情况都直接L和R在绝对值的情况下取最大值即可,然后每个点的答案取最大值(因为一直在取最大值,即移动次数一定大于等于每一个小点所需次数)
就是最终答案。
随便举例一种情况模拟了以下
代码
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
using namespace std;
typedef long long ll;
int n;
const int maxn=1e4+10;
int a[maxn]={},s[maxn]={};
void solve()
{
for(int i=1;i<=n;i++){
cin>>a[i];
s[i]=s[i-1]+a[i];
}
if(s[n]%n!=0){
cout<<-1<<endl;
return ;
}
int ave=s[n]/n;
ll ans=0,l=0,r=0;
for(int i=1;i<=n;i++){
l=(i-1)*ave-s[i-1];
r=(n-i)*ave-(s[n]-s[i]);
if(l>0&&r>0)
ans=max(ans,l+r);
else
ans=max(ans,max(abs(l),abs(r)));
}
cout<<ans<<endl;
}
int main()
{
IOS;
while(cin>>n){
if(n==0) break;
solve();
}
return 0;
}