前言
上周写完题结果一直没时间(老颓狗了 ,写博客,咕咕
链接
题目描述
现在有一组n个字符串和另一组共m个字符串,其中n个字符串会有一些在这m个字符串中,记其数量为a,现在问你如何在这m个字符串中连续地选取一段,选完这a个字符串并且选择个数最少
样例输入
3
hot
dog
milk
5
hot
dog
dog
milk
hot
样例输出
3
3
思路
找出a的值,然后用尺取法求出最小长度
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
int n, t, m, ans, ans1, sum;
int l[1000005], hash1[10005], hash2[10005];
bool b[100005];
string s;
struct str
{
int now, next;
}h[1000005];
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
{
cin>>s;
int hash_1 = 0, hash_2 = 0;
for(int j = 0; j < s.length(); ++j)
hash_1 = (hash_1 * 13331 + s[j]) % 10003;
for(int j = 0; j < s.length(); ++j)
hash_2 = (hash_2 * 10007 + s[j]) % 10003;
h[++t] = (str){hash_2, l[hash_1]}; l[hash_1] = t;
}
scanf("%d", &m);
ans = m;
for(int i = 1; i <= m; ++i)
{
cin>>s;
for(int j = 0; j < s.length(); ++j)
hash1[i] = (hash1[i] * 13331 + s[j]) % 10003;
for(int j = 0; j < s.length(); ++j)
hash2[i] = (hash2[i] * 10007 + s[j]) % 10003;
for(int j = l[hash1[i]]; j; j = h[j].next)
{
if(h[j].now == hash2[i] && !b[j]) {
ans1++;
b[j] = 1;
break;
}
}
}
for(int i = 1; i <= m - ans1 + 1; ++i)
{
memset(b, 0, sizeof(b));
sum = 0;
for(int j = i; j <= m; ++j) {
for(int k = l[hash1[j]]; k; k = h[k].next)
{
if(h[k].now == hash2[j]) {
if(!b[k]) {
b[k] = 1;
sum++;
}
break;
}
}
if(sum == ans1)
{
ans = min(ans, j - i + 1);
break;
}
}
}
printf("%d\n%d", ans1, ans);
}