题解:B4453 [海淀区普及组 2025 T1] 序列相似对

· · 题解

题解:B4453 [海淀区普及组 2025 T1] 序列相似对

1. 题目大意

我们需要计算数组 a 的子段的权值之和。在这里权值定义是:相同元素的对数 (i, j)(i < j 且 a_i = a_j)。

2. 方法思路

直接枚举所有子段会超时,因为子段数量为 O(n^2)。我们需要换个角度思考。对于每一对相等的元素 (i, j)(i < j 且 a_i = a_j),计算它出现在多少个子段中。

设子段的左端点为 L,右端点为 R。要使子段包含 i 和 j,必须满足:

**但是这样的时间复杂度显然超时,$n \le 10^5$,所以我们来考虑一下优化方法。** 对于数组 $p$(固定值的位置数组),计算贡献的公式可以变成: $$ \sum_{y=2}^{m}[(n-p_y+1)\times\sum_{x=1}^{y-1}p_x] $$ 然后我们在遍历的时候维护前缀和,令 $pre_i$ 是数组 $p$ 的前缀和数组,那么贡献就会等于 $pre_{i-1} \times (n-p_i+1)$。 这样每个值只需 $O(m)$ 时间,总时间 $O(n)$,非常聪慧。 ---------- ### 代码实现 ```cpp #include <bits/stdc++.h> using namespace std; #define int long long const int maxn = 1e5 + 10; int n, tot, a[maxn]; unordered_map<int, int> cnt; unordered_map<int, vector<int>> pos; signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; pos[a[i]].push_back(i); } for (auto &x : pos) { vector<int> v = x.second; int m = v.size(); if (m < 2) continue; int pre = v[0]; for (int j = 1; j < v.size(); j++) { tot += pre * (n - v[j] + 1); pre += v[j]; } } cout << tot << "\n"; return 0; } ``` 码风看着极为舒适。 AC 记录看这里:[AC](https://www.luogu.com.cn/record/256827620)