3405: [Usaco2009 open]grazing2 Mobile Barn Time Limit:3 Sec Memory limit:128 MB
Submit:55 solved:32
[Submit] [Status] [Discuss] Description John had N (2≤n≤1500) head cows, S (n≤s≤1,000,000) A word-lined barn. The distance between the adjacent barns is exactly 1. The cows are back in the shed, and the first cow is now in the Barn Pi. If two cows get too close, they can make the cows cranky. So John wanted to change a shed for some cows so that the distance between them was as large as possible, and even close. Jean D=trunc ((s-1)/(n-1) So John wants the final cow's status to be: The distance between the two adjacent cows is less than 1, and the maximum spacing is equal to D. Therefore, in the case of 8 sheds for 4 cows, placement conditions such as 1,3,5,8 or 1,3,6,8 are permissible, and situations such as 1,2,4,7 or 1,2,4,8 are not allowed. Help John move the cows and keep all cows moving at the smallest possible distance, while allowing the final placement to match John's heart. input line 1th enters N and S, and the next n lines enter a pi. Output An integer that represents the minimum moving distance and. Sample Input 5 2 8 1 3 9 sample Output 4
If you understand the problem, you can get AC.
Test instructions is like this, John wants to rearrange the position of each cow to meet
① 1th Cow in the leftmost, the nth cow at the right end
② the maximum distance between two cows is as small as possible.
③ finding the minimum number of moving steps
DP a bit ~
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
using namespace std;
int a[1505], dp[1505][1505];
int main (void)
{
int n, m, Len, I, J, D, ans;
scanf ("%d%d", &n, &len);
for (i=1;i<=n;i++)
scanf ("%d", &a[i]);
Sort (a+1, a+n+1);
ans = a[1]-1;
for (i=2;i<=n;i++)
a[i-1] = a[i]-1;
Len--, n--;
d = len/n;
m = len-n*d;
Memset (DP, a, sizeof (DP));
Dp[0][0] = 0;
for (i=1;i<=n;i++)
{
dp[i][0] = Dp[i-1][0]+abs (a[i]-i*d);
for (j=1;j<=m;j++)
dp[i][j] = min (Dp[i-1][j], dp[i-1][j-1]) +abs (a[i]-(i*d+j));
}
printf ("%d\n", Ans+dp[n][m]);
return 0;
}
/*
4 7
1 4 5 7
* *