思路
每次移动最外侧的兔子到中间的空隙, 相当于把外端空隙向内部推进,
最终所有兔子都会聚在较小端的空隙那侧, 较小端的空隙无法使用,其他所有空隙都能用。
结论
答案=总空隙数−较小端的空隙数。
代码
C++#include <bits/stdc++.h>
using namespace std;
const int N = 501;
int a[N];
int main() {
int t;
cin >> t;
while (t--) {
memset(a, 0, sizeof(a));
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
int tot = 0;
for (int i = 1; i < n; i++)
tot += a[i] - a[i - 1] - 1; //总空隙数
int l = a[1] - a[0] - 1; //左端空隙
int r = a[n - 1] - a[n - 2] - 1; //右端空隙
cout << tot - min(l, r) << endl; //输出
}
}
复杂度
时间复杂度: O(N) ,非常高效。