题解:P15351 [COCI 2025/2026 #4] 战斧牛排 / Tomahawk
解题思路:
这题目很 AT
此题让我们求矩阵中最大值与最小值之差,那么我们就得先求出最大值和最小值(有些废话)
我们分析一下操作。
进行
进行
进行
分析完后,我们可以发现,矩阵的最大值一定是第
这个最大值也好求,就是
最大值算起来还算容易,最小值却没那么简单。
首先判断有没有格子没有被操作过,条件则是如下(满足其中一者即可):
-
-
- 若上两个均不满足,则余下的最后一个条件为
\texttt D 操作的\max x=n 。
若满足以上条件之一,则所有格子都被覆盖了;反之有格子没被覆盖,矩阵中最小的元素为
经过上面的判断,我们已经知道的矩阵是否又被全部覆盖,接下来我们得求如果是的话矩阵的最小值。
通过前面的操作分析,我们可以进行讨论:
- 当
n 为偶数且\texttt L 操作的\max x 加上\texttt R 操作的\max x 等于n 时,此时最小的元素应为第1 行第\frac{n}{2} 或\frac {n}{2} + 1 列的元素。这两个元素分别为\texttt L 操作时x=\frac{n}{2} 的次数乘1 与\texttt D 操作时x=n 的次数乘1 之和,\texttt R 操作时x=\frac{n}{2} 的次数乘1 与\texttt D 操作时x=n 的次数乘1 之和,取最小值即可。 - 当
n 为奇数且\texttt L 操作的\max x 加上\texttt R 操作的\max x 大于或等于n 时,此时会有一个特殊情况就是第\lfloor \frac{n+1}{2}\rfloor 列在\texttt L 操作和\texttt R 操作x=\lfloor \frac{n+1}{2}\rfloor 时都会加上1 ,所以说此时第1 行第\lfloor \frac{n+1}{2}\rfloor 列的元素不一定是最小值,所以还要考虑其左右的两个元素(样例 #2 就是一个例子)我们求出这三个元素再求最小值即可。第1 行第\lfloor \frac{n+1}{2}\rfloor 列的元素的值为\texttt L 操作x = \lfloor \frac{n+1}{2}\rfloor 的次数乘1 加上\texttt R 操作x = \lfloor \frac{n+1}{2}\rfloor 的次数乘1 加上\texttt D 操作x=n 的次数乘1 的值,其左右两个元素的值分别为\texttt L 操作x = \lfloor \frac{n+1}{2}\rfloor 的次数乘2 加上\texttt L 操作x = \lfloor \frac{n+1}{2}\rfloor-1 的次数乘1 加上\texttt D 操作x=n 的次数乘1 的值,\texttt R 操作x = \lfloor \frac{n+1}{2}\rfloor 的次数乘2 加上\texttt R 操作x = \lfloor \frac{n+1}{2}\rfloor-1 的次数乘1 加上\texttt R 操作x = \lfloor \frac{n+1}{2}\rfloor 的次数乘1 加上\texttt D 操作x=n 的次数乘1 的值。 - 以上均不满足,且
\texttt D 操作的\max{x}=n ,则最小值为\texttt D 操作的x=n 的次数乘1 。
最后输出最大值减最小值的差即可。
代码如下:
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, q, x, tl, tr, td, ml, mr, md;
int jl, jr, jd;
int pl, pr;
char c;
signed main () {
cin >> n >> q;
while (q --) {
cin >> c >> x;
if (c == 'L') {
tl += x;
if (x == (n + n % 2) / 2) jl ++;
if (x == (n + n % 2) / 2 - 1) pl ++;
ml = max (ml, x);
} else if (c == 'R') {
tr += x;
if (x == (n + n % 2) / 2) jr ++;
if (x == (n + n % 2) / 2 - 1) pr ++;
mr = max (mr, x);
} else {
td += x;
if (x == n) jd ++;
md = max (md, x);
}
}
int mx = max (tl + td, tr + td), mi = 0;
if (n % 2 == 0 && ml + mr == n)
mi = min (jl, jr) + jd;
else if (n % 2 && ml + mr >= n)
mi = min ({jl + jr, pl + 2 * jl, pr + 2 * jr}) + jd;
else if (md == n)
mi = jd;
cout << mx - mi;
}