题解:P13662 「TPOI-5A」Luminescence
一道非常有趣的
首先发现前缀和后缀最小值变化时,我们一定可以确定当前位置的值,进而我们一定可以确定 0 和 1 的位置。
假设 0 在 1 的左侧,现在考虑 2 可以在哪里。
- 2 在 0 的左侧:由于前缀最小值的定义,我们一定可以确定 2 的位置。
- 2 在 1 的右侧:同上,我们可以确定 2 的位置。
- 2 在 0 和 1 中间:那么 2 的位置不会对当前的答案产生然后影响,因为如果想要 2 产生贡献,那么 0 和 1 是必要的,而在取到 0 和 1 后,区间一定包含 2。
更进一步的,我们可以继续确定 3 的位置,或发现 3 不影响答案。
综上,一个数的位置要么是确定的,要么不影响答案:那么无论怎样填数,权值都是一定的。
计数是简单的:考虑当前区间中有
代码如下:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
static const ll MOD = 998244353;
inline ll add(ll a, ll b) { a += b; if (a >= MOD) a -= MOD; return a; }
inline ll mul(ll a, ll b) { return (a * b) % MOD; }
const int N = 2e6 + 10;
int pre[N << 1], nxt[N << 1], pos[N << 1], s[N << 1], ck[N << 1];
void solve() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> pre[i];
for (int i = 1; i <= n; i++) cin >> nxt[i];
for (int i = 0 ; i <= n ; i ++) pos[i] = 0, s[i] = 0, ck[i] = 0;
ll ans = 1;
for (int i = 1; i <= n; i++) {
bool ppre = (i == 1) || (pre[i] < pre[i-1]);
bool nnxt = (i == n) || (nxt[i] < nxt[i+1]);
if (ppre || nnxt) {
int x = ppre ? pre[i] : nxt[i];
pos[x] = i; ck[i] = 1;
}
}
for (int i = 1 ; i <= n ; i ++) s[i] = s[i - 1] + !ck[i];
// for (int i = 1 ; i <= n ; i ++) cerr << ck[i] << ' '; cerr << '\n';
ll aans = 0, cnt = 0;
int L = n+1, R = 0;
for (int x = 0; x < n; x++) {
if (pos[x] > 0) {
L = min(L, pos[x]);
R = max(R, pos[x]);
}
else {
ans = mul(ans, s[R] - s[L - 1] - cnt);
cnt ++;
}
if (L <= R) {
aans = add(aans, mul(L, n - R + 1));
}
}
cout << mul(ans, aans) << "\n";
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T--) solve();
return 0;
}