题解:P13760 Clock Paradox
前置知识
- 双指针
- 前缀和
- 简单数学推导
解题思路
这显然是一道简单的数学题。
首先时间复杂度
但是我们对区间的枚举明显是多余的,可以用双指针来优化。我们考虑枚举一个
但它显然还可以更优。对于每个以
代码实现中有几个小细节需要注意:
代码实现
#include <bits/stdc++.h>
using namespace std;
constexpr int N(2e5 + 5), mod(1e9 + 7); // 注意:模数是 10^9 + 7
struct ModInt { // 自动取模结构体(仅实现了部分功能)
int value;
constexpr ModInt() : value(0) {}
int normalize(long long x) const {
x %= mod;
return static_cast<int>(x < 0 ? x + mod : x);
}
ModInt(long long v) : value(normalize(v)) {}
ModInt operator-() const {return {value ? mod - value : 0};}
ModInt qpow(int exp) const {
if (exp < 0) return qpow(-exp).inv();
ModInt base = *this, res(1);
while (exp) {
if (exp & 1) res *= base;
base *= base, exp >>= 1;
}
return res;
}
ModInt inv() const {return qpow(mod - 2);}
ModInt& operator+=(const ModInt& rhs) {
if ((value += rhs.value) >= mod) value -= mod;
return *this;
}
ModInt& operator-=(const ModInt& rhs) {
if ((value -= rhs.value) < 0) value += mod;
return *this;
}
ModInt& operator*=(const ModInt& rhs) {
value = (static_cast<long long>(value) * rhs.value) % mod;
return *this;
}
ModInt& operator/=(const ModInt& rhs) {
value /= rhs.value;
return *this;
}
friend ModInt operator+(ModInt lhs, const ModInt& rhs) {return lhs += rhs;}
friend ModInt operator-(ModInt lhs, const ModInt& rhs) {return lhs -= rhs;}
friend ModInt operator*(ModInt lhs, const ModInt& rhs) {return lhs *= rhs;}
friend ModInt operator/(ModInt lhs, const ModInt& rhs) {return lhs /= rhs;}
constexpr bool operator==(const ModInt& rhs) const {return value == rhs.value;}
constexpr bool operator!=(const ModInt& rhs) const {return value != rhs.value;}
constexpr bool operator<(const ModInt& rhs) const {return value < rhs.value;}
constexpr bool operator>(const ModInt& rhs) const {return value > rhs.value;}
constexpr bool operator<=(const ModInt& rhs) const {return value <= rhs.value;}
constexpr bool operator>=(const ModInt& rhs) const {return value >= rhs.value;}
friend ostream& operator<<(ostream& os, const ModInt& m) {return os << m.value;}
friend istream& operator>>(istream& is, ModInt& m) {
long long Value;
is >> Value, m = ModInt(Value);
return is;
}
explicit operator bool () {return value;}
} sum_a[N], sum_s[N];
int n, a[N];
map<int, int> last; // 这里选用适当的容器即可(注意:unordered_map 可能被卡成单次操作复杂度 O(N))
int main() {
ios::sync_with_stdio(false); // 关闭同步流
cin.tie(nullptr), cout.tie(nullptr);
cin >> n;
for (int i(1); i <= n; ++i) cin >> a[i];
for (int i(1); i <= n; ++i) // 预处理前缀和
sum_a[i] = sum_a[i - 1] + a[i];
for (int i(1); i <= n; ++i) // 预处理前缀和数组的前缀和
sum_s[i] = sum_s[i - 1] + sum_a[i];
ModInt ans(0);
for (int l(1), r(1); r <= n; ++r) {
if (last.count(a[r])) // 更新以 r 结尾的最大合法区间的左端点
l = max(l, last[a[r]] + 1); // 注意:last[a[r]] 可能小于等于 l
last[a[r]] = r; // 更新 last[a[r]]
ModInt len(r - l + 1); // 计算当前区间长度
// 累加答案
ans += (len * sum_a[r] - (sum_s[r - 1] - (l > 2 ? sum_s[l - 2] : 0)));
}
cout << ans;
return 0;
}