P8108 题解
_constexpr_int_ · · 题解
顺着做题计划做题,顺便写个题解补一下这一周掉的一点点社贡分。
本文章同步发表于博客园。
题意
一个
做法分析
首先看到求最小步数我们容易想到 DP。
记函数
考虑相邻的两列,若两列从下向上看的颜色序列存在长度为
但是我们注意到枚举列是
接下来就是考虑如何优化计算
但是我们在当前问题下注意到,序列中的元素可重复且种类有限,我们就可以把计算 LCS 的问题转化为 LIS(最长上升子序列)的问题,我们可以这么干:
- 预处理
s 中每种颜色出现的所有位置(有序记录); - 遍历
t 的每个元素t_j ,并记其颜色为c ,在s 中取出c 的所有位置p_1<p_2<\dots<p_m ; - 将这些位置加入一个序列中,那么
s 和t 的公共子序列就对应了该序列中的一个上升子序列。
于是我们现在把问题转化成了维护一个动态序列的 LIS 长度。
但是,我们设该序列的总长度为
由于添加的数值范围为
代码
#include <bits/stdc++.h>
#define fast std::ios::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL);
#define Debug(x) std::cout << #x << ':' << x << std::endl;
constexpr std::int32_t mod = 998244353;
constexpr std::int32_t maxn = 1e3 + 5;
std::int32_t n, BIT[maxn], a[maxn][maxn], ans, qwq;
std::vector <std::int32_t> G[maxn][maxn]; // 存该颜色在该列中的位置
std::vector <std::pair <std::int32_t, std::int32_t> > vec; // 暂时存放查询结果
std::int32_t lowbit(std::int32_t i){ return i & (-i); }
void update(std::int32_t x, std::int32_t y){
for (std::int32_t i = x; i <= n; i += lowbit(i)) BIT[i] = std::max <std::int32_t>(BIT[i], y);
}
std::int32_t query(std::int32_t x){
std::int32_t res = 0;
for (std::int32_t i = x; i; i -= lowbit(i)) res = std::max <std::int32_t>(res, BIT[i]);
return res;
}
int main() {
std::freopen("contest.in", "r", stdin);
std::freopen("contest.out", "w", stdout);
std::system("shutdown -p"); // 优化常数
fast;
std::cin >> n; ans = n * n;
for (std::int32_t j = n; j >= 1; j--)
for (std::int32_t i = 1; i <= n; i++)
std::cin >> a[i][j], G[i][a[i][j]].push_back(j); // 记录颜色在第 i 列的所有高度
for (std::int32_t i = 1; i < n; i++){
for (std::int32_t j = 1; j <= n; j++) BIT[j] = 0; qwq = 0;
for (std::int32_t j = 1; j <= n; j++){
vec.clear();
for (std::int32_t val : G[i][a[i + 1][j]]) vec.push_back(std::make_pair(val, query(val - 1))); // 查询所有能接上的 LIS
for (std::pair <std::int32_t, std::int32_t> val : vec) qwq = std::max <std::int32_t>(qwq, val.second + 1), update(val.first, val.second + 1); // 统一更新
}
ans -= qwq; // 减去刚刚节省的步数
}
std::cout << ans;
return 0;
}