【YbtOJ高效进阶 哈希-4】单词背诵

前言

上周写完题结果一直没时间(老颓狗了 ,写博客,咕咕

链接

hash - 4

题目描述

现在有一组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);
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值