#P2954. [USACO09OPEN] Grazing2 S

    ID: 1995 远端评测题 1000ms 125MiB 尝试: 0 已通过: 0 难度: 6 上传者: 标签>动态规划,dp递推2009USACO单调队列

[USACO09OPEN] Grazing2 S

Description

Farmer John has NN cows, numbered 1..N1..N, where 2N15002 \le N \le 1500. His newly painted barn has SS stalls in a single line, numbered 1..S1..S, where NS1,000,000N \le S \le 1{,}000{,}000. Each pair of adjacent stalls is at distance 11.

The cows have already gone to rest; cow ii is currently in stall PiP_i. Since cows get grumpy when they are too close together, Farmer John wants to move them so they are as spread out as possible and with similar gaps.

Let d=S1N1d = \left\lfloor \frac{S - 1}{N - 1} \right\rfloor (integer division). Farmer John wants the N1N - 1 distances between adjacent cows to each differ from dd by at most 11, and he also wants to maximize the number of these distances that are exactly equal to dd.

For example, with 44 cows and 88 stalls, placements 1,3,5,81, 3, 5, 8 and 1,3,6,81, 3, 6, 8 are allowed, but 1,2,4,71, 2, 4, 7 and 1,2,4,81, 2, 4, 8 are not allowed.

Help Farmer John spread the cows as efficiently as possible by computing the minimum total distance the cows must move to achieve such spacing. Ignore the distance for entering or leaving a stall.

Input Format

  • Line 1: Two space-separated integers NN and SS.
  • Lines 2..N+12..N+1: Line i+1i+1 contains a single integer PiP_i.

Output Format

  • Line 1: A single integer — the minimum total distance the cows must travel. This value is guaranteed to be less than 1,000,000,0001{,}000{,}000{,}000.
5 10 
2 
8 
1 
3 
9 

4 

Hint

1 2 3 4 5 6 7 8 9 10 Cow Locs | A | B | C | . | . | . | . | D | E | . |

Cows move from stall 2 to 3, 3 to 5, and 9 to 10. The total distance moved is 1 + 2 + 1 = 4. The final positions of the cows are in stalls 1, 3, 5, 8, and 10.

1 2 3 4 5 6 7 8 9 10 Init Stall | A | B | C | . | . | . | . | D | E | . | Final Stall | A | . | B | . | C | . | . | D | . | E | Distance moved | 0 | . | 1 | . | 2 | . | . | 0 | . | 1 |

Translated by ChatGPT 5