题解:P12672 「LAOI-8」近期我们注意到有网站混淆视听
0pts 解法
作为一道入门题,做法一定很简单对吧?
观察样例我们可以得到一个思路:如果字符串 LGR 和 CSP 那么我们只需一次交换改变其中一个即可,否则不需要交换。于是就有了下面的代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
char s[N];
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> s;
int n = strlen(s);
bool x = 0, y = 0;
for (int i = 0; i + 2 < n; i++)
{
if (s[i] == 'L' && s[i + 1] == 'G' && s[i + 2] == 'R') x = 1;
if (s[i] == 'C' && s[i + 1] == 'S' && s[i + 2] == 'P') y = 1;
}
if (x == 1 && y == 1) cout << 1 << '\n';
else cout << 0 << '\n';
}
return 0;
}
你说得对,但是它果不其然地拿到了
100pts 解法
显然只判断 LGR 和 CSP 是否同时出现会 WA,因为 LGR 或 CSP。
我们发现我们只要将 LGR 或 CSP 中的一个全部消灭即可完成目标,所以显然我们只需消灭数量更少的那一个即可。具体地,设 LGR 和 CSP 的数量分别为
接下来我们发现一次交换最多能同时消灭两个子串(在两个字串中各取一个字符交换即可)。若
故最终答案为:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
char s[N];
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> s;
int n = strlen(s);
int x = 0, y = 0;
for (int i = 0; i + 2 < n; i++)
{
if (s[i] == 'L' && s[i + 1] == 'G' && s[i + 2] == 'R') x++;
if (s[i] == 'C' && s[i + 1] == 'S' && s[i + 2] == 'P') y++;
}
cout << (min(x, y) + 1) / 2 << '\n'; // 等价于 ceil(min(x, y) / 2)
}
return 0;
}
时间复杂度