首页 > 代码库 > xtu summer individual 5 F - Post Office

xtu summer individual 5 F - Post Office

Post Office

Time Limit: 1000ms
Memory Limit: 10000KB
This problem will be judged on PKU. Original ID: 1160
64-bit integer IO format: %lld      Java class name: Main
 
 
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 51 2 3 6 7 9 11 22 44 50

Sample Output

9

Source

IOI 2000
 
解题:dp,dp[i][j]表示i个邮局负责j个村子时的最短距离和。距离和最少?肯定是选取的点如果在第i个与第n-i 个村子的中点(1 <= 1 <= n/2),距离和会最小啊!
 
 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long10 #define INF 0x3f3f3f3f11 using namespace std;12 int dp[35][301],x[301],n,m;13 int dis(int i,int j){14     int sum = 0;15     while(i < j) sum += x[j--]-x[i++];16     return sum;17 }18 int main(){19     int i,j,k;20     while(~scanf("%d%d",&m,&n)){21         memset(dp,0,sizeof(dp));22         for(i = 1; i <= m; i++){23             scanf("%d",x+i);24             dp[1][i] = dis(1,i);25         }26         for(i = 2; i <= n; i++){27             for(j = i; j <= m; j++){28                 dp[i][j] = INF;29                 for(k = i-1; k < j; k++)30                     dp[i][j] = min(dp[i][j],dp[i-1][k]+dis(k+1,j));31             }32         }33         cout<<dp[n][m]<<endl;34     }35     return 0;36 }
View Code