pku 1160 Post Office

#include <iostream> #include <cmath> #include <climits> using namespace std; int pos[301]; int v[31][301]; int cost[301][301]; //状态转移方程为: // 前i个邮局控制前j个村庄的最小距离和: // v[i][j] = min{v[i-1][k]+cost[k+1][j]}(i-1 <= k <= j-1); int main() { int V, P; scanf("%d%d", &V, &P); for(int i = 1; i <= V; ++i) scanf("%d", &pos[i]); //从村落i到村落j由一个邮局控制时的最短距离和 for(int i = 1; i <= V; ++i) for(int j = i; j <= V; ++j) { int mid = (i+j) >> 1; for(int k = i; k <= j; ++k) cost[i][j] += abs(pos[mid] - pos[k]); } //initial for(int i = 1; i <= V; ++i) v[1][i] = cost[1][i]; //dp for(int i = 2; i <= P; ++i) for(int j = i; j <= V; ++j) { int min = INT_MAX; for(int k = i-1; k <= j-1; ++k) if(v[i-1][k] + cost[k+1][j] < min) min = v[i-1][k] + cost[k+1][j]; v[i][j] = min; } printf("%d/n", v[P][V]); return 0; }  

你可能感兴趣的:(Office,include)