解題思路
求每位選手左右連續可擊敗的人數最大值。
若目前選手能擊敗堆頂,堆頂可被彈出;曾被堆頂彈掉的選手也被它支配,利用支配的傳遞性,當前選手也能擊敗那些人。
彈到無法擊敗的堆頂,它就是最近的左側阻擋者;若無堆頂,可一路擊敗到左界。反向再掃一次得到右側阻擋者。
每人可擊敗的人數為兩阻擋者之間的格數減自己,因為任何更遠對手都會先被最近阻擋者阻住。每個索引至多入棧出棧一次。
時間 O(N),空間 O(N);Python以array存攻防、左界與堆疊,並逐行讀取,避免split全部1.5百萬行。
Step-by-step animation
三位攻防(1,1)、(3,3)、(2,2)示例
步驟 1 / 3
步驟 1
示例攻防(1,1)、(3,3)、(2,2)。
左1
中3
右2
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n), d(n), L(n), s;
for (int i = 0; i < n; i++)
cin >> a[i] >> d[i];
auto win = [&](int i, int j) {
return a[i] >= a[j] && d[i] >= d[j] && (a[i] > a[j] || d[i] > d[j]);
};
for (int i = 0; i < n; i++) {
while (!s.empty() && win(i, s.back()))
s.pop_back();
L[i] = s.empty() ? -1 : s.back();
s.push_back(i);
}
s.clear();
int ans = 0;
for (int i = n - 1; i >= 0; i--) {
while (!s.empty() && win(i, s.back()))
s.pop_back();
int r = s.empty() ? n : s.back();
ans = max(ans, r - L[i] - 2);
s.push_back(i);
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。