程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> poj1160 Post Office

poj1160 Post Office

編輯:C++入門知識

poj1160 Post Office


Description

There is a straight highway with villages alongside the highway. The highway is represented as an integer axis, and the position of each village is identified with a single integer coordinate. There are no two villages in the same position. The distance between two positions is the absolute value of the difference of their integer coordinates.

Post offices will be built in some, but not necessarily all of the villages. A village and the post office in it have the same position. For building the post offices, their positions should be chosen so that the total sum of all distances between each village and its nearest post office is minimum.

You are to write a program which, given the positions of the villages and the number of post offices, computes the least possible sum of all distances between each village and its nearest post office.

Input

Your program is to read from standard input. The first line contains two integers: the first is the number of villages V, 1 <= V <= 300, and the second is the number of post offices P, 1 <= P <= 30, P <= V. The second line contains V integers in increasing order. These V integers are the positions of the villages. For each position X it holds that 1 <= X <= 10000.

Output

The first line contains one integer S, which is the sum of all distances between each village and its nearest post office.

Sample Input

10 5
1 2 3 6 7 9 11 22 44 50

Sample Output

9

這題是區間dp經典,看了別人的代碼,自己寫出來了。可以先設兩個數組sum[i][j]和dp[i][j],sum[i][j]表示第i和第j個村莊之間建一個郵局並且這些村莊的花費都和這個郵局計算得到的最小花費,dp[i][j]表示前i個村莊中間j個郵局並且這i個村莊的花費計算都與這些郵局有關的最小花費。

那麼前i個村莊中建j個郵局的最小花費可以由前k個村莊中建i-1個郵局的最小花費加上第k個郵局到第i個郵局建一個郵局的最小花費轉移過來,即dp[i][j]=min(dp[i][j],dp[k][j-1]+sum[k+1][i]);

這裡的初始條件是dp[i][1]=sum[1][i].

當郵局數為1時,我們把郵局建在中間就行了,當郵局有多個時,就有sum[i][j]=sum[i][j-1]+pos[j]-pos[(i+j)/2]。

 

#include
#include
#define maxn 350
#define inf 88888888
int min(int a,int b){
	return a

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved