【洛谷】P9242 [蓝桥杯 2023 省 B] 接龙数列 的题解
题目传送门
思路
首先一个数我们只需要关注其首位数字和末位数字,定以 f i \mathit{f}_{i} fi 为以数字 i i i 结尾的最长接龙序列的长度。对于每个数字设其首位数字为 a a a ,末尾数字为 b b b,则有转移方程: f b = max ( f b , f a + 1 ) \mathit{f}_{b}=\max(\mathit{f}_{b},\mathit{f}_{a}+1) fb=max(fb,fa+1)。
最后在 f 0 \mathit{f}_{0} f0, f 1 … f 9 \mathit{f}_{1} \dots \mathit{f}_{9} f1…f9 取一个最大值 a n s ans ans,答案则为 n − a n s n − a n s n−ans。
代码
#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int n, t, a[200005], b[200005], f[10];
int main() {
int t = 1;
while(t --) {
n = read();
for (int i = 1; i <= n; i ++) {
int x;
cin >> x;
b[i] = x % 10;
string s = to_string(x);
a[i] = s[0] - '0';
}
for (int i = 1; i <= n; i ++) {
f[b[i]] = max(f[b[i]], f[a[i]] + 1);
}
int ans = 0;
for (int i = 0; i <= 9; i ++) {
ans = max(ans, f[i]);
}
write(n - ans);
}
return 0;
}