Post Office Problem
来源:互联网 发布:通达信编程3000例 编辑:程序博客网 时间:2024/06/06 11:00
On one line there are n houses. Give you an array of integer means the the position of each house. Now you need to pick k position to build k post office, so that the sum distance of each house to the nearest post office is the smallest. Return the least possible sum of all distances between each village and its nearest post office.
样例
Given array a = [1,2,3,4,5]
, k = 2.return 3
.
挑战
Could you solve this problem in O(n^2)
time ?
class Solution {public: /** * @param A an integer array * @param k an integer * @return an integer */ int postOffice(vector<int>& A, int k) { // Write your code here int n = A.size(); sort(A.begin(), A.end()); int cost[n][n]; memset(cost, 0, n*n*sizeof(int)); for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { int mid = i + (j-i)/2; cost[i][j] = 0; for (int k = i; k <= j; k++) { cost[i][j] += abs(A[k] - A[mid]); } } } int buf[n][k+1]; memset(buf, 0, n*(k+1)*sizeof(int)); for (int i = 0; i < n; i++) { for (int j = 1; j <= k; j++) { if (j == 1) { buf[i][j] = cost[0][i]; } else if (j > i) { buf[i][j] = 0; } else { buf[i][j] = INT_MAX; for (int k = 0; k < i; k++) { buf[i][j] = min(buf[i][j], buf[k][j-1] + cost[k+1][i]); } } } } return buf[n-1][k]; }};
0 1
- Post Office Problem
- Codeforces Problem 702D Road to Post Office(分类讨论)
- Post Office
- Post Office
- Post Office
- Post Office
- pku 1160 Post Office
- POJ 1160 Post Office
- pku 1160 Post Office
- pku1160 Post Office
- PKU1190 post office
- poj 1160 Post Office
- POJ 1160 Post Office
- DP: Post Office
- Post Office (P1160)
- poj 1160 Post Office
- poj1160(Post Office)
- POJ 1160 Post Office
- 合并有序的两个数字数组为一个
- 标准java http和 apach httpclient总结
- 接口文档管理,版本管理工具,阿里RAP的windows下部署
- NSPredicate
- Mac OS X ,Windows,Unix-like上的“换行”
- Post Office Problem
- C语言指针初始化的必要性以及指针变量与指针值的用法
- Freemarker中大于小于的用法
- 3.Android support design FloatingActionButton
- sax解析xml
- 字符串
- 在Linux x86_64环境运行xv6系统
- 原生JS实现全选与反选和jquery全选与反选
- C语言文件打开和二进制打开方式的区别