QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#585651 | #9313. Make Max | Nanako7_ix | TL | 0ms | 3652kb | C++14 | 2.7kb | 2024-09-23 21:40:16 | 2024-09-23 21:40:17 |
Judging History
answer
#include<bits/stdc++.h>
#define pii pair<int, int>
#define endl "\n"
#define setpre(x) fixed << setprecision(x)
#define FOR(i, l, r) for(int i = l; i <= r; ++i)
#define ROF(i, l, r) for(int i = r; i >= l; --i)
#define fi first
#define se second
using namespace std;
using LL = long long;
constexpr int MAXN = 5e5 + 10;
constexpr int inf = 0x3f3f3f3f;
constexpr LL INF = 0x3f3f3f3fffffffff;
struct DSU {
int n;
vector<int> f;
vector<int> siz;
DSU(int n) : n(n) {
f.resize(n + 1);
siz.assign(n + 1, 1);
iota(f.begin(), f.end(), 0);
}
int find(int x) {
if(f[x] == x) return x;
return f[x] = find(f[x]);
}
void merge(int x, int y) {
x = find(x), y = find(y);
if(x != y) f[y] = x, siz[x] += siz[y];
}
int size(int x) {
return siz[find(x)];
}
};
void solve() {
int n;
cin >> n;
vector<int> a(n + 1);
FOR(i, 1, n) cin >> a[i];
DSU dsu(n);
vector<int> l(n + 1), r(n + 1);
stack<int> stk;
for(int i = 1; i <= n; ++i) {
while(!stk.empty() && a[stk.top()] <= a[i]) stk.pop();
if(!stk.empty()) l[i] = stk.top();
else l[i] = -1;
stk.push(i);
}
while(!stk.empty()) stk.pop();
for(int i = n; i >= 1; --i) {
while(!stk.empty() && a[stk.top()] <= a[i]) stk.pop();
if(!stk.empty()) r[i] = stk.top();
else r[i] = -1;
stk.push(i);
}
FOR(i, 2, n) {
if(a[i] == a[i - 1]) {
dsu.merge(i, i - 1);
}
}
priority_queue<pii, vector<pii>, greater<pii>> q;
FOR(i, 1, n) {
if(i == dsu.find(i)) {
q.push({a[i], i});
}
}
LL ans = 0;
while(dsu.size(1) != n) {
int u = q.top().se;
q.pop();
// 重新找到左右边界的根节点
int L = l[dsu.find(u)], R = r[dsu.find(u)];
assert(~L || ~R); // 确保至少有一个有效的区间
ans += dsu.size(u);
// 按值大小合并,更新 DSU
if(L == -1) {
dsu.merge(R, u);
} else if(R == -1) {
dsu.merge(L, u);
} else if(a[dsu.find(L)] < a[dsu.find(R)]) {
dsu.merge(L, u);
} else {
dsu.merge(R, u);
}
// 更新左右边界和优先队列
int new_root = dsu.find(u);
if(l[new_root] != -1) l[new_root] = l[dsu.find(L)];
if(r[new_root] != -1) r[new_root] = r[dsu.find(R)];
q.push({a[new_root], new_root});
}
cout << ans << endl;
}
signed main() {
cin.tie(0), cout.tie(0) -> sync_with_stdio(0);
int t = 1;
cin >> t;
while(t--) solve();
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 0ms
memory: 3652kb
input:
4 2 1 2 2 2 2 7 1 1 1 2 2 2 2 3 1 2 3
output:
1 0 3 3
result:
ok 4 number(s): "1 0 3 3"
Test #2:
score: -100
Time Limit Exceeded
input:
2 198018 875421126 585870339 471894633 383529988 625397685 944061047 704695631 105113224 459022561 760848605 980735314 847376362 980571959 329939331 644635272 326439858 752879510 837384394 175179068 182094523 397239381 1199016 185143405 279638454 252374970 822030887 860312140 137248166 993229443 164...