【NOIP2025】字符串模板
andysheng
·
·
算法·理论
Hash
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int P = 131;
unsigned long long f[N], p[N];
int n;
string str;
void Hash_prework()
{
n = str.size() - 1;
p[0] = 1;
for(int i = 1; i <= n; i++)
{
f[i] = f[i - 1] * P + str[i] - '0' + 1;
p[i] = p[i - 1] * P;
}
}
int Hash_query(int l, int r)
{
return f[r] - f[l - 1] * p[r - l + 1];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> str, str = " " + str;
Hash_prework();
int m;
cin >> m;
for(int i = 1; i <= m; i++)
{
int l1, r1, l2, r2;
cin >> l1 >> r1 >> l2 >> r2;
if(Hash_query(l1, r1) == Hash_query(l2, r2)) cout << "Yes\n";
else cout << "No\n";
}
return 0;
}
最小表示法
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
string str;
cin >> str, str = " " + str;
for(int i = 1; i <= n; i++) str += str[i];
int i = 1, j = 2, k = 0;
while(i <= n && j <= n)
{
for(k = 0; k < n && str[i + k] == str[j + k]; k++);
if(k == n) break;
if(str[i + k] > str[j + k])
{
i = i + k + 1;
if(i == j) j++;
}
else
{
j = j + k + 1;
if(i == j) i++;
}
}
int ans = min(i, j);
for(int i = ans; i <= ans + n - 1; i++) cout << str[i];
cout << '\n';
return 0;
}