517. Super Washing Machines(超级洗衣机)

来源:互联网 发布:apache cxf 教程 编辑:程序博客网 时间:2024/05/16 23:59

问题描述
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.
Example1
这里写图片描述
Example2
这里写图片描述
Example3
这里写图片描述
Note:
1.The range of n is [1, 10000].
2.The range of dresses number in a super washing machine is [0, 1e5].
解题思路
该题目的要求使得每台洗衣机具有一样的衣服数,即是将数组中的数字平均分给数组中的每一个元素。则衣服总数是所有洗衣机个数的倍数,那么sum%size应该为0,这构成了第一个条件,而且达到平衡时的衣服数为target=sum/size。另外,每台洗衣机每次只能移动一件衣服到邻接的洗衣机处,所以我们需要找出达到平衡时需要移动最多步数的洗衣机,而计算在每台洗衣机移动步数时,我们可以可引入balance变量来记录达到平衡需要的步数,使用累加的方法,可以巧妙地计算到每台洗衣机的移动步数,从左开始算,负数代表从左移动的步数,正数则是从右移动的步数,那么其绝对值则是最少移动步数。比如,已经有5件衣服需要经过第i台机器进行传递,同时这台机器本身又溢出了2件衣服,那么就需要传递7件衣服,共计7步。然后用一个变量实时记录最大值即可。遍历完数组中所有的元素再求最大值,就可得出真正的最少步数。

代码展示

#include <iostream>#include <stdlib.h>#include <vector>#include <string>using namespace std; class Solution {public:    int findMinMoves(vector<int>& machines) {        int sum = 0, size = machines.size();        for (int i = 0; i < size; ++i) sum += machines[i];        if (sum % size != 0) return -1;                      //如果不能均分,则返回-1。         int target = sum / size, totalstep = 0, balance = 0;        for (int i = 0; i < size; ++i) {                      //对数组中每个元素遍历             balance += machines[i] - target;                  //找出经过该元素的最大流量             totalstep = max(totalstep, max(machines[i] - target, abs(balance)));         }        return totalstep;    }};int main(){    int n;    vector<int> nums;    cout<<"请输入向量长度:";    cin>>n;    int num[n];    for(int i = 0;i<n;i++){        cin>>num[i];        nums.push_back(num[i]);    }    Solution solution;    int result=solution.findMinMoves(nums);     cout<<result<<endl;}

运行结果展示
这里写图片描述
这里写图片描述
这里写图片描述