其实早就想练DP了,毕竟自己的DP都是XJB乱写的。。然后不小心看到四边形不等式就钻进来瞧瞧。。
这题好像初中就做过,才发现竟然是IOI的题?!
考虑到邮局并没有先后顺序,所以从左往右依次设置邮局,然后得到转移方程如下:
设d[i][j]为使用i个邮局负责前j个村庄的最小费用,w[i][j]为在i到j村庄中设置一个邮局的费用
d[i][j]=min{d[i-1][k]+w[k+1][j]} (k=i-1..j-1)
感觉直接转移复杂度O(p*v*v)并不会超时吧。。不过不优化一下做这题就没意义了。。
事实上四边形不等式的证明我还不是很懂。。然而这并不影响我们做题。。好像是yjq说过我们可以用普通的DP把决策方案算出来然后打表。。然后决策单调性什么的都是非常显然的了。。
然后就把d[i][j]对应的策略s[i][j]给打了出来。。
0 0 0 0 0 0 0 0 0 0
0 1 1 3 3 3 3 7 8 8
0 0 2 3 3 5 5 7 8 8
0 0 0 3 3 5 6 7 8 8
0 0 0 0 4 5 6 7 8 9
发现i确定时,k随着j递增。。因此可以把复杂度降成O(p*v)
对w可以前缀和+差分预处理一下。。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cmath>
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define inf 1e9
#define eps 1e-8
#define mem(a) memset(a,0,sizeof(a))
#define ll long long
#define succ(x) (1<<x)
#define lowbit(x) (x&(-x))
#define sqr(x) ((x)*(x))
#define NM 305
#define pi 3.141592653
using namespace std;
int read(){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
return f*x;
}
int n,m,a[NM],b[NM],w[NM][NM],d[NM][NM];
int main(){
//freopen("data.in","r",stdin);
n=read();m=read();
inc(i,1,n)a[i]=read();
inc(i,1,n)b[i]=b[i-1]+a[i];
inc(i,1,n)inc(j,i,n)w[i][j]=b[j]-b[(i+j)/2]-b[(i+j-1)/2]+b[i-1];
inc(j,1,n)d[1][j]=w[1][j];
inc(i,2,m){
int t=i-1;
inc(j,i,n){
d[i][j]=inf;
inc(k,t,j-1)
if(d[i-1][k]+w[k+1][j]<d[i][j])d[i][j]=d[i-1][k]+w[k+1][j],t=k;
}
}
//inc(i,1,m){inc(j,1,n)printf("%d ",s[i][j]);putchar('\n');}
printf("%d\n",d[m][n]);
return 0;
}
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 20394 | Accepted: 11013 |
Description
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
Output
Sample Input
10 5 1 2 3 6 7 9 11 22 44 50
Sample Output
9
Source
[Submit] [Go Back] [Status] [Discuss]