Codeforces 766A: Mahmoud and Longest Uncommon Subsequence

Codeforces 766A C++ 一解.

分析

两个字符串的最长不公共子序列被定义为最长的仅为其中一个字符串的子序列的字符串.

对于两个长度不相同的字符串 (不妨设 $a,b$ 且 $a$ 的长度较长), 一个非常直观的想法是: 因为一个字符串的子序列的长度必须不大于该串的长度, 只要选取 $a$ 本身作为所求的子序列, 其肯定是 $a$ 的子序列, 而不是 $b$ 的子序列.

而对于长度相同的情况, 我们同样可以使用类似的思路: 若两个串不相同, 我们总能选择其中一个串本身作为所求的子序列, 这样其一定不会是另一个串的子序列; 若两个串完全相同, 此时我们就无法找到一个串 (根据题意, 包括空串) 作为所求的子序列, 只能输出 $-1$.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
string a, b;

cin >> a >> b;

if (a == b)
{
cout << -1 << endl;
}
else
{
cout << max(a.length(), b.length()) << endl;
}

return 0;
}

Codeforces 766A: Mahmoud and Longest Uncommon Subsequence

https://blog.tamako.work/acmoi/codeforces/766a/

Posted on

2022-07-30

Updated on

2022-07-30

Licensed under

Comments