6924.Houses and Schools

Time Limit: 1s Memory Limit: 512MB

There are $n$ houses on a street, numbered $1,2,\dots,n$ . The distance of houses $a$ and $b$ is $|a-b|$ . You know the number of children in each house.

Your task is to establish $k$ schools in such a way that each school is in some house. Then, each child goes to the nearest school. What is the minimum total walking distance of the children if you act optimally?

Input Format(From the terminal/stdin)

The first input line has two integers $n$ and $k$ : the number of houses and the number of schools. The houses are numbered $1,2\dots,n$ .

After this, there are $n$ integers $c_1,c_2,\dots,c_n$ : the number of children in each house.

  • $1 \le k \le n \le 3000$
  • $1 \le c_i \le 10^9$

Output Format(To the terminal/stdout)

Print the minimum total distance.

Sample Input

Copy
6 2
2 7 1 4 6 4
 · \n
 · · · · · \n

Sample Output

Copy
11
  \n

Houses 2 and 5 will have schools.

Source: CSES, Advanced Techniques, 2087

Submit

请先 登录

© 2025 FAQs