题解 CF1506C 【Double-ended Strings】
概述
题号 | 难度 | \(AC\)时间及记录 |
---|---|---|
\(\texttt{CF1506C}\) | \(\texttt{洛谷难度:暂无评定}\) | \(\texttt{On 2021/03/26}\) |
解析
这是一道简单题。
题意不难理解。
其实,我们稍微想一想,就知道:
- 如果 \(a\) 非空,删除 \(a\) 的第一个字符。
- 如果 \(a\) 非空,删除 \(a\) 的最后一个字符。
- 如果 \(b\) 非空,删除 \(b\) 的第一个字符。
- 如果 \(b\) 非空,删除 \(b\) 的最后一个字符。
这一大段话,意思就是:
- 求 \(a\) 和 \(b\) 的最长公共子串。
然后我们可以用一个 \(\mathcal{O(nm)}\) 的 \(Dp\) 求出解。
这个不会请自己百度吧。
(\(n\),\(m\) 是两字符串长度)
顺便还是说一句:求出最长公共子串以后,我们还需要处理一下答案。
AA=A.size(),BB=B.size();
cout<<AA+BB-2*findLength(A,B)<<endl;
代码
/*
Author:Xsmyy
Problem:CF1506C
Date:2021/03/25
*/
#include<bits/stdc++.h>
#define BetterIO ios::sync_with_stdio(false)
using namespace std;
int N,K;
bool Flag[101];
inline int findLength(string A,string B) {
int asize=A.size();
int bsize=B.size();
int dp[asize][bsize];
int max = 0;
for(int i=0,j=0; i<asize; i++){
if(A[i] == B[j]){
dp[i][j] = 1;
max = 1;
}else{
dp[i][j] = 0;
}
}
for(int i=0,j=0; j<bsize; j++){
if(A[i] == B[j]){
dp[i][j] = 1;
max = 1;
}else{
dp[i][j] = 0;
}
}
for(int i=1; i<asize; i++){
for(int j = 1; j<bsize; j++){
if(A[i] == B[j]){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = 0;
}
if(dp[i][j] > max){
max = dp[i][j];
}
}
}
return max;
}
int main(void)
{
BetterIO;
register int Case;
cin>>Case;
while(Case--)
{
register string A,B;
cin>>A>>B;
register int AA,BB;
AA=A.size(),BB=B.size();
cout<<AA+BB-2*findLength(A,B)<<endl;
}
return 0;
}
不要妄图追上西坠的太阳,而是要在黎明前就等着它!