我试图解决一个问题,其中包括寻找最低成本。这个问题可以表述为:给定n建筑物,并为每个建筑物的高度和成本给出。现在的任务是找到最低成本,使所有的建筑物变成等于相同的高度。每栋建筑物可以被认为是垂直堆积的砖,其中每块砖可以以与该建筑物相关的成本来添加或去除。如何找到最低成本?
例如: 假设n = 3的建筑物的高度分别为1,2,3和10,100,1000。
这里,最低的成本将等于120
这里是链接的问题:
http://www.spoj.pl/problems/KOPC12A/
一个明显的答案是要找到与每个高度相关的成本对于所有的建筑物,然后给他们输出最小的成本。这是O(n^2)。
为了寻找更好的解决方案,我试着找到高度与成本比值最小值的高度。然后所有的建筑物必须等于这个高度并计算成本并作为输出。但是这给了我错误的回答。 这里是我的实现:
基于下面的答案我已经使用加权平均值更新了我的代码,但仍然没有working.It给了我错误的答案。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
long long fun(int h[],int c[],int optimal_h,int n){
long long res=0;
for(int i=0;i<n;i++){
res += (abs(h[i]-optimal_h))*c[i];
}
return res;
}
int main()
{
int t;
cin>>t;
for(int w=0;w<t;w++){
int n;
cin>>n;
int h[n];
int c[n];
int a[n];
int hh[n];
for(int i=0;i<n;i++){
cin>>h[i];
hh[i]=h[i];
}
sort(hh,hh+n);
for(int i=0;i<n;i++)
cin>>c[i];
long long w_sum=0;
long long cost=0;
for(int i=0;i<n;i++){
w_sum += h[i]*c[i];
cost += c[i];
}
int optimal_h;
if(cost!=0){
optimal_h=(int)((double)w_sum/cost + 0.5);
if(!binary_search(hh,hh+n,optimal_h)){
int idx=lower_bound(hh,hh+n,optimal_h)-hh;
int optimal_h1=hh[idx];
int optimal_h2=hh[idx-1];
long long res1=fun(h,c,optimal_h1,n);
long long res2=fun(h,c,optimal_h2,n);
if(res1<res2)
cout<<res1<<"\n";
else
cout<<res2<<"\n";
}
else{
long long res=fun(h,c,optimal_h,n);
cout<<res<<"\n";
}
}
else
cout<<"0\n";
}
return 0;
}
任何想法如何解决这个问题?
不要将其标记为[C标记。 – ApprenticeHacker 2012-03-20 17:01:40
而@dark_shadow,请不要链接到您的代码的外部网站。只要把它放在这里,并正确格式化。 – 2012-03-20 17:02:32
小费,不知道它是否有用;计算建筑物高度之间的加权平均值,其中权重是成本。 – 2012-03-20 17:08:49