It is clear that S represents the initial magic value, k is the number of selected items, and x is given in the problem.
Noting that x is large but k and n are small, we can define a state that tracks the i-th item, the number of selected items j, and the sum modulo k as l. The goal is to maximize the initial magic value, as higher values reduce time spent. We then brute force the total number of selections and trnasition states accordingly, with a time complexity of O(n^3k).
The core idea is enumeration and simulation.
</details>ABC134F
This problem took a long time to understand, and the solution seemed confusing.
Considering the absolute values, it's natural to split contributions. For each position i, if the matched number is larger than i, the absolute value contribution becomes -i; otherwise, it becomes i.
For each pair, the contribution depends on the comparison between the two numbers.
We define a state that represents the current position i, the count of unmatched numbers j, and the strange value k. Transitions involve several cases:
- Filling i with itself: no contribution.
- Merging with future elements: positive contribution.
- Merging with previous elements: negative contribution.
- One merging with previuos and one with future: multiply by 2.
Finally, handle negative strange values by shifting the k dimension by n\*n.
<details><summary>View code</summary>```
void solve() {
cin >> n >> m;
ll maxn = n * n * 2;
dp[0][0][n * n] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= maxn; k++) {
add(dp[i][j][k], dp[i - 1][j][k]);
if (j) add(dp[i][j][k], dp[i - 1][j][k] * 2ll % M);
if (j && k + i * 2 <= maxn) add(dp[i][j][k], dp[i - 1][j - 1][k + 2 * i]);
if (j < i - 1 && k - i * 2 >= 0) add(dp[i][j][k], dp[i - 1][j + 1][k - 2 * i] * (j + 1) * 1ll % M);
}
}
}
printf("%lld", dp[n][0][m + n * n]);
}
This problem was solved quickly by a senior student last year, but I didn't focus on it at the time.
Initially, it seems challenging. However, considering that a_i contributes only when it matches a_lsta_i, and all intermediate elements must not match, we can define a state f_i representing the answer up to the i-th position. The transition is:
f_i = f_{lsta_i + 1} + a_i + S_i - S_{i-1}, where S_i is the prefix sum.
The reason for adding 1 is to ensure that elements before lsta_i can still match with those outside the range.
</details></div>