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.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