题目描述
有n个村庄分布在一条直线上,每个村庄可以用一个坐标xi来进行描述。现在,你需要建设m个邮局,使得每个村庄到离它最近的邮局的距离之和最小。
输入
第一行两个正整数n,m。第二行n个递增的整数,表示x1~xn。
输出
输出一行一个整数,为最小的距离之和。
样例输入
10 5 1 2 3 6 7 9 11 22 44 50
样例输出
9
提示
对于100%的数据,满足1≤n≤300,1≤m≤30,1≤xi≤10000。
#include <bits/stdc++.h> #include <algorithm> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define wuyt main typedef long long ll; #define HEAP(...) priority_queue<__VA_ARGS__ > #define heap(...) priority_queue<__VA_ARGS__,vector<__VA_ARGS__ >,greater<__VA_ARGS__ > > template<class T> inline T min(T &x,const T &y){return x>y?y:x;} template<class T> inline T max(T &x,const T &y){return x<y?y:x;} ///#define getchar()(p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++) ///char buf[(1 << 21) + 1], *p1 = buf, *p2 = buf; ll read(){ll c = getchar(),Nig = 1,x = 0;while(!isdigit(c) && c!='-')c = getchar(); if(c == '-')Nig = -1,c = getchar(); while(isdigit(c))x = ((x<<1) + (x<<3)) + (c^'0'),c = getchar(); return Nig*x;} #define read read() const ll inf = 1e15; const ll INF = 0x3f3f3f3f; const int maxn = 2e6 + 7; const int mod = 1e9 + 7; ll gcd(ll a,ll b) { ll t; while(b!=0) { t=a%b; a=b; b=t; } return a; } ll qPow(ll x, ll k) { ll res = 1; while(k) { if(k&1) res=(res*x); k>>=1; x=(x*x); } return res; } ll maxx=-1; ll minn=inf; ll a[maxn]; ll num2[maxn]; ll num[maxn]; ll ans; int sum=0; map<string,ll> mp; vector<ll> vet; priority_queue <int ,vector<int> ,greater<int> > xiaogen; queue <ll> duilie; priority_queue <int ,vector<int> ,less<int> > que; char s1[30],s2[30]; char ss[70]; int judge[100]; int dit[400][400]; ll res[400][400]; int main() { int n=read,m=read; for(int i=1;i<=n;i++) num[i]=read; ///先计算距离 for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++) dit[i][j]=dit[i][j-1]+abs(num[j]-num[(i+j)/2]); } for(int i=1;i<=n;i++){ res[i][i]=0;///自己到自己 res[i][1]=dit[1][i]; } for(int i=2;i<=m;i++){ for(int j=i+1;j<=n;j++){ res[j][i]=INF; for(int k=i-1;k<j;k++) res[j][i]=min(res[j][i],res[k][i-1]+dit[k+1][j]); ///cout<<res[j][i]<<endl; } } cout<<res[n][m]<<endl; return 0; } /************************************************************** Problem: 15405 Language: C++ Result: 正确 Time:20 ms Memory:50788 kb ****************************************************************/
48位大咖的思考法则、工作方式、逻辑体系