Idea: first because to make the distance as large as possible, so the cow 11 in the No. 1th Cattle Barn, cow n must be in the s number of the barn, and then consider DP.
Because the total distance is s-1, and then to make the number of segments with a length of D as much as possible, then the rest must be the number of d+1, that is, S (n-1) *d.
Then f[i][j] to ensure that the first I a cattle barn legal and the front length of the number of d+1 is the answer of J, then the position of the first barn is actually (i-1) *d+j.
And because the I-1 barn can only be separated by D or d-1, so there is F[i][j]=min (F[i-1][j],f[i-1][j-1]) +abs (a[i]-(i-1) *d-j)
The answer is f[n][m].
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include < algorithm>using namespace std; #define MAXN 1505 int n,s;int A[maxn];int F[MAXN][MAXN]; inline int Read () { int x=0;char ch=getchar (); for (;ch< ' 0 ' | | Ch> ' 9 '; Ch=getchar ()); for (; ch>= ' 0 ' &&ch<= ' 9 '; Ch=getchar ()) x=x*10+ch-' 0 '; return x;} inline void print (int x) { if (x>=10) print (X/10); Putchar (x%10+ ' 0 ');} int main () { n=read (), s=read (); int d= (S-1)/(n-1), m=s-(n-1) *d; for (int i=1;i<=n;i++) a[i]=read (); Sort (a+1,a+n+1); memset (F,63,sizeof (f)), f[1][1]=a[1]-1; for (int i=2;i<=n;i++) for (int j=1;j<=m&&j<=i;j++) f[i][j]=min (f[i-1][j],f[i-1][j-1]) + ABS (a[i]-d* (I-1)-j); Print (f[n][m]); return 0;}
bzoj3405:[usaco2009 open]grazing2 Mobile Barn