# 题目大意
管理大大给修下 $\text{Markdown}$ 吧,严重影响做题体验啊。
这道题的意思很简单就是给你一个长度是 $n$ 的环,这个环上不均匀的分布着 $n$ 头奶牛。一头奶牛移动要花费的代价是距离的平方,现在让你求出使得每个点上都有一头奶牛需要花费的最小代价,注意,奶牛只能顺时针移动。
# 解题思路
首先断环成链这个大家应该都知道,就是将原序列 copy 一份放到后面去。
然后考虑如果一头奶牛在移动的过程中没有经过其他奶牛,那这一定是最优的方案。还有就是如果一个点有奶牛,那将奶牛运到它顺时针防线上离它连续一段 $0$ 的最后一个 $0$。
枚举初始位置,从初始位置开始如果遇到有牛的地方,就将这个位置放到优先队列 (小根堆) 里,在往后扫的过程中将其慢慢移动过来。
直观的说就是下面这个式子:
$$a^2+b^2<(a+b)^2$$
# 附上代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, a[
2003], cnt, ans =
1e9;
priority_queue <
int, vector<
int>, greater<
int> >
Q;
bool flag =
true;
int main() {
scanf("%d", &
n);
for(
int i=
1; i<=n; i++
) {
scanf("%d", &
a[i]);
a[i+n] =
a[i];
}
static int tmp;
for(
int i=
1; i<=n; i++
) {
cnt =
0, flag =
true;
for(
int j=i; j<=i+n-
1; j++
) {
if(Q.empty() && a[j] ==
0) {flag =
false;
break;}
tmp =
a[j];
while (tmp--
) Q.push(j);
tmp =
Q.top(), Q.pop();
cnt += (tmp-j) * (tmp-
j);
}
if(!flag)
continue;
ans =
min(ans, cnt);
}
printf("%d", ans);
}
转载于:https://www.cnblogs.com/bljfy/p/9629879.html