Fast Food
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1403 Accepted Submission(s): 609
To make this more precise, the management of McBurger has issued the following specification: You will be given the positions of n restaurants along the highway as n integers d1 < d2 < ... < dn (these are the distances measured from the company's headquarter, which happens to be at the same highway). Furthermore, a number k (k <= n) will be given, the number of depots to be built.
The k depots will be built at the locations of k different restaurants. Each restaurant will be assigned to the closest depot, from which it will then receive its supplies. To minimize shipping costs, the total distance sum, defined as
must be as small as possible.
Write a program that computes the positions of the k depots, such that the total distance sum is minimized.
The input file will end with a case starting with n = k = 0. This case should not be processed.
Output a blank line after each test case.
6 3 5 6 12 19 20 27 0 0
Chain 1 Total distance sum = 8
思路:f[a][b] a到b之间只有一个补给站时的最优路径长。dp[a][b]前b个店设有a个补给站的最优值。
f[a][b]=min(f[a-1][c]+f[c+1][b])(a-1<=c<=b-1)
#include<iostream>
#include<cstring>
using namespace std;
const int mm=210;
const int oo=1e9;
int f[mm][mm],dp[33][mm],data[mm];
int m,n;
inline int fabs(int x)
{
return x>0?x:-x;
}
int main()
{ int cas=0;
while(cin>>m>>n)
{ if(m==0&&n==0)break;
for(int i=1;i<=m;i++)cin>>data[i];
memset(f,0,sizeof(f));
for(int i=1;i<=m;i++)
for(int j=i+1;j<=m;j++)
{ for(int k=i;k<=j;k++)
f[i][j]+=fabs(data[(i+j)/2]-data[k]);///i到j中只设一个补给站的最优值
}
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
for(int j=i;j<=m;j++)
dp[i][j]=oo;
for(int i=1;i<=m;i++)///边界
dp[1][i]=f[1][i];
for(int i=2;i<=n;i++)///补给站的个数
for(int j=i;j<=m;j++)///店的个数
{ for(int k=i-1;k<j;k++)
{int z=dp[i-1][k]+f[k+1][j];
///cout<<z<<"z"<<i<<" "<<j<<endl;
dp[i][j]=z<dp[i][j]?z:dp[i][j];
}
}
cout<<"Chain "<<++cas<<"\n";
cout<<"Total distance sum = "<<dp[n][m]<<"\n";
cout<<"\n";
}
}
1555



被折叠的 条评论
为什么被折叠?



