滑动窗口 + 优化
不难发现如果 i - j > n / 2
,由于 n - (i - j) = n + j - i <= n / 2
,因此可以对应成在 i
和 j + n
之间运送货物,
代价为 a[i] + a[j] + n + j - i
可是O(n ^ 2)必然超时
不难发现他是维护一个区间内的最大值,答案取决于a[j] - j
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n;
int w[N], q[N];
inline void solve()
{
cin >> n;
for (int i = 1; i <= n; i ++ ) cin >> w[i], w[i + n] = w[i];
int res = 0, hh = 0, tt = -1;
int len = n / 2;
for (int i = 1; i <= n * 2; i ++ )
{
if (hh <= tt && i - len > q[hh]) hh ++;
if (res < i - q[hh] + w[q[hh]] + w[i])
res = i - q[hh] + w[q[hh]] + w[i];
while (hh <= tt && w[q[tt]] - q[tt] <= w[i] - i) tt --;
q[ ++ tt] = i;
}
cout << res << endl;
}
int main()
{
cin.tie(nullptr) -> sync_with_stdio(0);
solve();
return 0;
}