题解P1321[单词覆盖还原]

算法
题目来源P1321https://www.luogu.com.cn/problemnew/show/P1321

一共只会出现以下字符:

b o y g i r l .

boygirl两串中可能出现的重叠形式全部替换成某个字符,例如我用a..替换boy的组合,用z...替换girl的组合

得出boygirl可能的拆分如下:

1
2
boy bo oy b o y
girl gir irl gi ir rl g i r l

输出时单个字母b o y g i r l可在和a z一同判断

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
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;

char str[260];

void init();
void replace_boy(char*, int);
void replace_girl(char*, int);

int main()
{
cin >> str;
init();
int boy = 0, girl = 0;
for (int i = 0, len = strlen(str); i < len; i++)
{
if (str[i] == 'a' || str[i] == 'b' || str[i] == 'o' || str[i] == 'y')
boy++;
else if (str[i] == 'z' || str[i] == 'g' || str[i] == 'i' || str[i] == 'r' || str[i] == 'l')
girl++;
}
cout << boy << endl << girl;
cin.get(); cin.get();
return 0;
}
void init()
{
//替换
replace_boy("boy", 3);
replace_boy("bo", 2);
replace_boy("oy", 2);

replace_girl("girl", 4);
replace_girl("gir", 3);
replace_girl("irl", 3);
replace_girl("gi", 2);
replace_girl("ir", 2);
replace_girl("rl", 2);

}
void replace_boy(char* sub, int len)
{
char *boy = strstr(str, sub);
//在字符串str1中找str2,返回其首次出现的地址
while (boy != NULL)
{
*boy = 'a';
for (int i = 1; i < len; i++)
*(boy + i) = '.';
boy = strstr(str, sub);//找下一个
}
}
void replace_girl(char* sub, int len)
{
char *girl = strstr(str, sub);
while (girl != NULL)
{
*girl = 'z';
for (int i = 1; i < len; i++)
*(girl + i) = '.';
girl = strstr(str, sub);
}
}

本文作者:Xecades

本文链接:https://blog.xecades.xyz/articles/solution-p1321/

文章默认使用 CC BY-NC-SA 4.0 协议进行许可,使用时请注意遵守协议。

评论