xrf有一个镜子,可以把任何接触镜面的东西变成原来的两倍——只是,因为是镜子嘛,增加的那部分是反的。比如一条项链,我们用AB来表示,不同的字母表示不同颜色的珍珠。如果把B端接触镜面的话,镜子会把这条项链变为ABBA。如果再用一端接触的话,则会变成ABBAABBA(假定xrf只用项链的某一端接触镜子)。给定最终的项链,请编写程序输出xrf没使用镜子之前,最初的项链可能的最小长度。
时间: 2024-03-11 14:50:05 浏览: 49
这个问题可以用字符串匹配来解决。假设原始的项链是s,目标项链是t,我们可以将s复制一遍得到ss,那么目标项链t一定是ss的一个子串。现在我们需要找到最短的s使得ss包含t。
我们可以使用KMP算法来找到ss中的t子串,然后计算出t在ss中的起始位置p,那么s的长度就是p+len(t)/2,其中len(t)是t的长度。这里除以2是因为xrf的镜子将t的长度增加了一倍,但是我们只需要计算原始s的长度,因此需要除以2。
下面是C语言实现的代码:
```c
#include <stdio.h>
#include <string.h>
// 计算字符串s的next数组
void get_next(char* s, int* next) {
int len = strlen(s);
int i = 0, j = -1;
next[0] = -1;
while (i < len) {
if (j == -1 || s[i] == s[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
// KMP算法查找子串
int kmp(char* s, char* t, int* next) {
int slen = strlen(s);
int tlen = strlen(t);
int i = 0, j = 0;
while (i < slen && j < tlen) {
if (j == -1 || s[i] == t[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == tlen) {
return i - j;
} else {
return -1;
}
}
int main() {
char s[101], t[101];
int next[101];
scanf("%s", t);
int len = strlen(t);
// 构造ss
for (int i = 0; i < len; i++) {
s[i] = t[i];
s[i+len] = t[i];
}
s[2*len] = '\0';
// 计算next数组
get_next(t, next);
// 在ss中查找t
int pos = kmp(s, t, next);
if (pos == -1) {
printf("error\n");
} else {
printf("%d\n", len - pos + len/2);
}
return 0;
}
```
输入格式为目标项链t,输出为最小的原始项链s的长度。注意代码中的字符串长度为101,这是因为在输入项链时需要加上一个字符串结尾符号'\0'。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)