题目大意
两个字符串u和v之间的编辑距离是将u转换为v的最小编辑操作次数。可以对字符串应用三种编辑操作:插入字符,删除字符,用不同字符替换某个字符。
例如,我们可以用四次替换将hello转换为world,因此编辑距离最多为4。您可以用两次替换和一次插入将wally转换为walter,因此编辑距离最多为3。计算两个字符串之间的编辑距离是一个众所周知的问题,有许多应用。
当前任务是计算一个字符串到最接近的回文串的编辑距离。回文串是从后往前读和从前往后读相同的字符串,例如madam。
hello到最接近回文串的编辑距离仅为2:我们可以用两次编辑操作将hello转换为ollo,或hllh,或elle。
编写一个程序,可以找到一个单词到最接近回文串的距离。
思路讲解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| auto dfs=[&](auto && self,ll l,ll r) -> ll { if (r==l) { return 0; } if (r-l==1) { return s[l]!=s[r]; } if (dp[l][r]!=INF) { return dp[l][r]; } dp[l][r]=min({self(self,l+1,r-1)+(s[l]!=s[r]), self(self,l,r-1)+1, self(self,l+1,r)+1, }); return dp[l][r]; };
|
AC代码
AC
https://codeforces.com/gym/106084/submission/361098919
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <bits/stdc++.h> #define all(vec) vec.begin(),vec.end() #define lson(o) (o<<1) #define rson(o) (o<<1|1) #define SZ(a) ((long long) a.size()) #define debug(var) cerr << #var <<":"<<var<<"\n"; #define cend cerr<<"\n-----------\n" #define fsp(x) fixed<<setprecision(x)
using namespace std;
using ll = long long; using ull = unsigned long long; using DB = double; using LD = long double;
using CD = complex<double>;
static constexpr ll MAXN = (ll)1e6+10, INF = (1ll<<61)-1; static constexpr ll mod = 998244353; static constexpr double eps = 1e-8; const double pi = acos(-1.0);
ll lT;
bool check(const string &s) { ll sz=s.size(); for (int i=0;i<sz;++i) { if (s[i]!=s[sz-i-1]) { return false; } } return true; } void Solve() { string s; cin>>s; if (check(s)) { cout<<0<<"\n"; return; } ll N=s.size(); s.insert(s.begin(),'#'); vector dp(N+2,vector<ll>(N+2,INF)); auto dfs=[&](auto && self,ll l,ll r) -> ll { #ifdef LOCAL assert(r>=l); #endif if (r==l) { return 0; } if (r-l==1) { return s[l]!=s[r]; } if (dp[l][r]!=INF) { return dp[l][r]; } dp[l][r]=min({self(self,l+1,r-1)+(s[l]!=s[r]), self(self,l,r-1)+1, self(self,l+1,r)+1, }); return dp[l][r]; }; ll ans=dfs(dfs,1,N); cout<<ans<<"\n"; }
signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> lT; while(lT--) Solve(); return 0; }
|
心路历程(WA,TLE,MLE……)