分析
大致一看,不过是求最长接龙子序列的长度,然后答案就是n-最长接龙子序列的长度,但是如何来求呢?同学们很容易想到要去用动态规划,每加入一个第i个数Ai,然后在0~i-1个数中找能与Ai对接的最长的接龙子序列,不过这种方法时间复杂度为O(n^2),超时了,这里有一种更为巧妙的方法。我们发现对于首位数字和尾位数字均在 0 ~9范围内,我们可以用dp[i](0<=i<=9)表示末尾数字为i的最长接龙子序列长度。那么由此能得到递推公式,每加入一个数字m,dp[back(m)]=max(dp[back(m)],dp[front(m)]+1),(其中back(m)表示数字m的尾位,front(m)表示数字m的首位),然后给出我们的代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define endl '\n'
int getint(int n){//获取数字首位
while(n>=10)n/=10;
return n;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,m;
cin>>n;
vector<int> dp(10,0);
int result=0;
for(int i=0;i<n;i++){
cin>>m;
dp[m%10]=max(dp[m%10],dp[getint(m)]+1);
}
for(int i=0;i<10;i++){
result=max(result,dp[i]);
}
cout<<n-result<<endl;
return 0;
}
怎么样?是不是代码非常简洁,这道题真的是太妙了。