题解:P13465 [GCJ 2008 #1C] Increasing Speed Limits

· · 题解

思路

状态转移方程为: $$ dp_i = 1 + \sum_{j < i, a_j < a_i} dp_j $$ 最终答案为: $$ \sum_{i = 1}^n dp_i $$ 但是,直接转移是 $O(n ^ 2)$ 的,考虑优化。 从小到大枚举 $i$,$j < i$ 的限制可以忽略,那么只需要求当前所有 $a_j < a_i$ 的位置的 $dp_j$ 的和,可以使用树状数组维护,时间复杂度优化为 $O(n\log n)$。 记得离散化。 ### 代码 ```cpp #include <bits/stdc++.h> #define int long long using namespace std; const int MAXN = 5e5 + 10; const int N = 5e5; const int mod = 1e9 + 7; int T, n, m, x, y, z; int A[MAXN], a[MAXN], lsh[MAXN]; int c[MAXN], ans; int lowbit(int x) { return x & -x; } void add(int x, int y) { for (int i = x; i <= N; i += lowbit(i)) c[i] = (c[i] + y) % mod; } int sum(int x) { int res = 0; for (int i = x; i; i -= lowbit(i)) res = (res + c[i]) % mod; return res; } signed main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> T; for (int t = 1; t <= T; t++) { memset(c, 0, sizeof(c)); ans = 0; cin >> n >> m >> x >> y >> z; for (int i = 0; i < m; i++) cin >> A[i]; for (int i = 0; i < n; i++) { a[i + 1] = A[i % m]; lsh[i + 1] = a[i + 1]; A[i % m] = (x * A[i % m] + y * (i + 1)) % z; } sort(lsh + 1, lsh + n + 1); int tot = unique(lsh + 1, lsh + n + 1) - lsh - 1; for (int i = 1; i <= n; i++) a[i] = lower_bound(lsh + 1, lsh + tot + 1, a[i]) - lsh; for (int i = 1; i <= n; i++) { int qwq = sum(a[i] - 1) + 1; ans = (ans + qwq) % mod; add(a[i], qwq); } cout << "Case #" << t << ": " << ans << '\n'; } return 0; } ```