.article-info-tag,button{text-transform:uppercase}.day,.postMeta,.postSticky{position:relative}.postTitle a:link,html{-webkit-tap-highlight-color:transparent}#blog-calendar,.code-copay-btn,.code-hljs-len,.hidden{visibility:hidden}#EntryTag,#blogTitle h1{margin-top:20px}#EntryTag a,.postSticky{background:#6fa3ef}#blogTitle h1 a:hover,.dayTitle a,a,a:active,a:link,a:visited{color:#5c8ec6}#calendar table a:hover,#navList a:hover,.postDesc a:hover,a:active,a:hover,a:link,a:visited,button{text-decora…ryTag a:visited{color:#666}#BlogPostCategory a,#EntryTag a{height:20px;line-height:20px;color:#fff!important;padding:3px 5px;border-radius:3px;margin:2px 5px 0;text-decoration:none;font-size:14px}#BlogPostCategory a:hover,#EntryTag a:hover{transition:all .3s linear 0s;opacity:.8}#topics .postDesc{padding-left:0;width:100%;text-align:left;color:#666;margin-top:5px;background:0 0}.feedbackListSubtitle-louzhu:after,.feedbackListSubtitle:after,.feedbackListSubtitle:before{top:11px;right:100%;left:-1

CF1506C Double-ended Strings 题解

Description

给两个字符串,可以从头或尾删除字母使得两个字符串相等,最小化删除次数(空串也相等)。

Solution

我们会发现按照这样的删除方式,只有连续的公共子串不会被删除。所以我们可以把问题转化成求两个子串的最长连续公共子串长度。即:

设字符串为 \(s,t\)\(f[i][j]\) 表示 \(s\)\(s_i\) 结尾,\(t\)\(t_j\) 结尾的最长连续子串长度,则可以分类转移:

\[\begin{cases} f[i][j]=f[i-1][j-1]\quad(s[i]=s[j])\\ f[i][j]=0\quad otherwise\\ \end{cases}\]

时间复杂度为 \(\Theta(ta_{length}b_{length})\)

Code

/*If you are full of hope,you will be invincible*/
#define ri register int
typedef long long ll;
std::mt19937 hpy(time(nullptr)+(unsigned long long)(new char));
using std::cin;
using std::cout;
constexpr int inf=0x3f3f3f3f;
std::string s1,s2;
int ans;
int f[30][30];
int t;
inline void solve() {
    memset(f,0,sizeof f);
    int len1 = s1.size(),len2 = s2.size();
    for(int i = 0;i < len1;++i) {
        for(int j = 0;j < len2;++j) {
            if(s1[i] == s2[j]) {
                if(!i || !j) f[i][j] = 1;
                else f[i][j] = f[i-1][j-1] + 1;
            }
        }
    }
    int mx = 0;
    for(int i = 0;i < len1;++i) {
        for(int j = 0;j < len2;++j) mx = std::max(f[i][j],mx);
    }

    ans = len1 + len2 - mx*2;//最长公共子串的贡献为其长度的两倍(在a中的贡献和在b中的贡献)
}
int main(int argc,const char *argv[]){
	std::ios::sync_with_stdio(false);
    cin >> t;
    while(t--) {
        cin >> s1 >> s2;
        solve();
         cout << ans << '\n';
    }
	return 0;
}
posted @ 2021-04-08 19:33  feicheng  阅读(70)  评论(0编辑  收藏  举报