ACM: 动态规划 poj 1160 终于有点…
2016-05-19 23:20
417 查看
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 题意: 在n个村庄里面选取m个当作邮政局, 使得每个点到最近的邮政局的为它的距离差的绝对值. 现在要全部点距离和最小. 解题思路: 1. 动态规划题, 先找规划状态: dp[i][j]: 前i个村庄设置j个邮政局的最小距离差和. 2. 动态转移方程: dp[i][j] = min(dp[i][j],dp[k][j-1]+dist[k+1][j]); dist[k+1][j]: 表示点k+1到点j的邮政设置一个的时候点的最小距离. (j-1 <= k <= i-1) 3. dist[i][j]可以通过预处理实现. 代码: #include <cstdio> #include <iostream> #include <cstring> using namespace std; #define MAX 303 const int INF = (1<<30); int n, m; // n: point, m: post office; int a[MAX]; int dist[MAX][MAX]; int dp[MAX][MAX]; inline int min(int a,int b) { return a < b ? a : b; } int abs(int a) { return a > 0 ? a : -a; } int main() { // freopen("input.txt","r",stdin); while(scanf("%d %d",&n,&m) != EOF) { memset(dist,0,sizeof(dist)); for(int i = 1; i <= n; ++i) { scanf("%d",&a[i]); } for(int i = 1; i <= n; ++i) { for(int j = i+1; j <= n; ++j) { int mid = (i+j)/2; //取i,j的中点. for(int k = i; k <= j; ++k) { dist[i][j] += abs(a[k]-a[mid]); } } }
相关文章推荐
- java-ThreadLocal是解决线程安全问题
- 给未来的你 — 李开复在2011…
- ACM: 动态规划 poj 1692
- ACM: 动态规划 poj 1190
- 虚拟机下安装ubuntu后root密码设置
- Ubuntu15.10GNOME安装后配置
- JavaScript跨域(1):什么是跨域,如何跨域
- Jmeter(5)逻辑控制器(Logic Controller)
- ACM: 动态规划 poj 1141
- ACM: 动态规划 poj 2479
- 动态规划: poj1505改编题
- 动态规划: 航线设置 (求最大升序长…
- ACM: 优先队列 数据结构题 toj 290…
- ACM: 数论题 toj3343 同 poj 1061
- ACM:最大子树 动态规划题 toj2676
- ACM: 数论题 toj 1721
- ACM: 序列中找最小逆序对 杂题 TOJ…
- mapReduce概念及用法
- ACM: 简单最小生成树 图论题 poj 1…
- ACM: spfa+dfs 图论题 poj 2679