【发布时间】:2012-04-05 04:26:57
【问题描述】:
我正在尝试解决一个包括找到最低成本的问题。这个问题可以表述为:给定 n 个建筑物,并且给定每栋建筑物的高度和成本。现在的任务是找到最低成本,以便所有建筑物的高度相同。每座建筑物都可以被视为垂直的砖堆,其中每块砖都可以通过与该建筑物相关的成本来添加或移除。
例如: 假设有 n=3 栋建筑物,高度分别为 1,2,3,成本分别为 10,100,1000。
在这里,最低成本将等于 120。
这里是问题的链接:
http://www.spoj.pl/problems/KOPC12A/
一个明显的答案是找出与所有建筑物的每个高度相关的成本,然后将它们的最低成本作为输出。这是 O(n^2)。
为了寻找更好的解决方案,我尝试找到高度/成本比率最小值的高度。然后所有建筑物必须等于这个高度并计算成本并作为输出给出。但这给了我错误的答案. 这是我的实现:
根据以下答案,我已使用加权平均值更新了我的代码,但仍然无法正常工作。它给了我错误的答案。
#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;
}
知道如何解决这个问题吗?
【问题讨论】:
-
和@dark_shadow,请不要为您的代码链接到外部站点。只需将其放在这里并正确格式化即可。
-
一个小技巧,不知道有没有用;计算建筑物高度之间的加权平均值,其中权重是成本。
-
旁白:C++没有变长数组,避免
int h[n];;更喜欢std::vector<int> h(n);。 -
这个问题可能跑题了。您的任务可以描述为 LAD 问题:最小化
sum(abs(h[i] - x) * c[i])。见en.wikipedia.org/wiki/Least_absolute_deviations
标签: c++ algorithm linear-algebra