# 阿里巴巴5月5日综合算法题详解

average = （warehouse[1]+warehouse[2]+...+warehouse[n])/n

1. 第0步（从仓库1向仓库n运送k）:花费代价为 |k|，
2. 第1步（确保仓库1的余量为average）：需要花费代价为
|warehouse[1]-average-k|

也就是从1向2伙从2向1运输

3. 第2步（确保仓库2的余量为average）：代价为
|warehouse[2]+warehouse[1]-average-k-average|=|warehouse[1]+warehouse[2]-2*average-k|

...
n-1.第n-1步：代价为

|warehouse[1]+warehouse[2]+...+warehouse[n-1]-(n-1)*average-k|

(warehouse[n]+k)+warehouse[1]+warehouse[2]+...+warehouse[n-1]-(n-1)*average-k=(warehouse[1]+warehouse[2]+...+warehouse[n])-(n-1)*average=average

|k|+|warehouse[1]-average-k|+|warehouse[1]+a[2]-2*average-k|+...+|warehouse[1]+warehouse[2]+...+warehouse[n-1]-(n-1)*average-k|

sum[i] = warehouse[1]+warehouse[2]+...+warehouse[i]-i*average

|k|+|sum[1]-k|+|sum[2]-k|+...+|sum[n-1]-k|

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include<string>

using namespace std;

const int X = 100000;
double sum[X],warehouse[X];
int n;

double Abs(double x)
{
return max(x,-x);
}

int _tmain(int argc, _TCHAR* argv[])
{
while(true)
{
double total = 0;
double mid=0;
cout<<"请输入仓库数目：";
cin>>n;
//读入n个仓库的值，并计算总数
for(int i=1;i<=n;i++)
{
cout<<"请输入第"<<i<<"个仓库的存量：";
cin>>warehouse[i];
total += warehouse[i];
}
//计算每个仓库应该最终存储的值
double average = total/n;
//计算sum数组
for(int i=1;i<n;i++)
sum[i] = warehouse[i]+sum[i-1]-average;
//排序后打算去中位数
//sort采用半开半闭区间，所以排序为0～n-1
sort(sum,sum+n);
//这个可以自己举个数字就知道了
if(n%2!=0)
{
mid = sum[n/2];
}
else
{
mid=(sum[n/2]+sum[n/2-1])/2;
}
cout<<"应该从1开始,运输"<<mid<<"货物,然后依次保证符合条件即可"<<endl;
double ans = Abs(mid);
for(int i=1;i<n;i++)
ans += Abs(sum[i]-mid);
cout<<"总成本花费是:"<<ans<<endl;
cout<<"----------------------------------------------------------------------"<<endl;
}
return 0;
}

posted @ 2013-06-02 16:13  lazycoding  阅读(1279)  评论(3编辑  收藏  举报