[USACO09OCT] Barn Echoes G
题目描述
The cows enjoy mooing at the barn because their moos echo back, although sometimes not completely. Bessie, ever the excellent
secretary, has been recording the exact wording of the moo as it goes out and returns. She is curious as to just how much overlap there is.
Given two lines of input (letters from the set a…z, total length in the range 1…80), each of which has the wording of a moo on it, determine the greatest number of characters of overlap between one string and the other. A string is an overlap between two other strings if it is a prefix of one string and a suffix of the other string.
By way of example, consider two moos:
moyooyoxyzooo
yzoooqyasdfljkamo
The last part of the first string overlaps ‘yzooo’ with the first part of the second string. The last part of the second string
overlaps ‘mo’ with the first part of the first string. The largest overlap is ‘yzooo’ whose length is 5.
POINTS: 50
奶牛们非常享受在牛栏中哞叫,因为她们可以听到她们哞声的回音。虽然有时候并不能完全听到完整的回音。Bessie 曾经是一个出色的秘书,所以她精确地纪录了所有的哞叫声及其回声。她很好奇到底两个声音的重复部份有多长。
输入两个字符串(长度为 1 1 1 到 80 80 80 个字母),表示两个哞叫声。你要确定最长的重复部份的长度。两个字符串的重复部份指的是同时是一个字符串的前缀和另一个字符串的后缀的字符串。
我们通过一个例子来理解题目。考虑下面的两个哞声:
moyooyoxyzooo
yzoooqyasdfljkamo
第一个串的最后的部份 yzooo
跟第二个串的第一部份重复。第二个串的最后的部份 mo
跟第一个串的第一部份重复。所以 yzooo
跟 mo
都是这
2
2
2 个串的重复部份。其中,yzooo
比较长,所以最长的重复部份的长度就是
5
5
5。
输入格式
* Lines 1…2: Each line has the text of a moo or its echo
输出格式
* Line 1: A single line with a single integer that is the length of the longest overlap between the front of one string and end of the other.
样例 #1
样例输入 #1
abcxxxxabcxabcd
abcdxabcxxxxabcx
样例输出 #1
11
提示
‘abcxxxxabcx’ is a prefix of the first string and a suffix of the second string.
题解
之间区间hash一下 前面的 和 后面的 就行
Code
#include <bits/stdc++.h>
#define int long long
using namespace std;
// 存储输入的两个字符串
string a, b;
// 读取输入的两个字符串函数
void read()
{
cin >> a >> b; // 从标准输入读取两个字符串
}
// 用于存储字符串 a 和 b 每个位置的哈希值
int cnt_a[110], cnt_b[110];
// 哈希计算中的基数
int p = 40;
// 取模的值
const int mod = 1e9 + 7;
// 解决问题的主要函数
void solve()
{
// 计算字符串 a 第一个字符的哈希值
cnt_a[0] = a[0] - 'a' + 1;
// 计算字符串 a 其余位置的哈希值
for (int i = 1; i < a.size(); i++)
{
cnt_a[i] = (cnt_a[i - 1] * p + a[i] - 'a' + 1) % mod;
}
// 计算字符串 b 第一个字符的哈希值
cnt_b[0] = b[0] - 'a' + 1;
// 计算字符串 b 其余位置的哈希值
for (int i = 1; i < b.size(); i++)
{
cnt_b[i] = (cnt_b[i - 1] * p + b[i] - 'a' + 1) % mod;
}
int ans = 0;
int cnt = 1;
for (int i = 1; i <= min(a.size(), b.size()); i++)
{
cnt *= p;
cnt %= mod;
// 比较字符串 a 和 b 的子串是否相同
if (cnt_a[i - 1] == (cnt_b[b.size() - 1] + mod - cnt * cnt_b[b.size() - i - 1] % mod) % mod)
{
ans = max(ans, i);
}
if (cnt_b[i - 1] == (cnt_a[a.size() - 1] + mod - cnt * cnt_a[a.size() - i - 1] % mod) % mod)
{
ans = max(ans, i);
}
}
cout << ans << endl;
}
// 主函数
signed main()
{
read(); // 调用读取函数
solve(); // 调用解决问题的函数
return 0;
}
标签:cnt,string,int,哈希,字符串,mod,刷题,奇遇记
From: https://blog.csdn.net/resco/article/details/144199598