对于一个长度为 K 的整数数列:A1, A2, . . . , AK,我们称之为接龙数列当且仅当 Ai 的首位数字恰好等于 Ai−1 的末位数字 (2 ≤ i ≤ K)。
例如 12, 23, 35, 56, 61, 11 是接龙数列;12, 23, 34, 56 不是接龙数列,因为 56的首位数字不等于 34 的末位数字。所有长度为 1 的整数数列都是接龙数列。
现在给定一个长度为 N 的数列 A1, A2, . . . , AN,请你计算最少从中删除多少个数,可以使剩下的序列是接龙序列?
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int a[N];
int n;
int ans=0;
int get_first(int x)
{
int res=0;
while(x)
{
res=x%10;
x=x/10;
}
return res;
}
int get_last(int x){
return x%10;
}
//u表示当前考虑到了第几位。
//last表示,方案中已经选了的最后一个数字是多少
//cnt表示,方案中一共有多少个数字
void dfs(int u,int cnt,int last)
{
if(u>=n)
{
ans=max(ans,cnt);
return;
}
//优化
if(n-u+cnt<=ans)
{
return ;
}
//第u位数选如果选这个数字
//就必须和前面最后一个数字构成接龙序列。
if(last==-1||get_last(last)==get_first(a[u]))
{
dfs(u+1,cnt+1,a[u]);
}
//第u位数不选
dfs(u+1,cnt,last);
}
void solve()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
dfs(0,0,-1);
cout<<n-ans<<endl;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
t=1;
while(t--)
solve();
}