UVA 12338

本文介绍了一种利用字符串hash技术计算任意两个单词相似度的方法,详细解释了算法原理,并通过实例代码展示了实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:

      给你n个单词,问你任意两个单词的相似度是多少。(相似度就是两个单词从第一个单词开始一共有多少个字母是相同的)

解决方法:

      字符串hash

我的代码:

#include <cstdio>
#include <string>
#include <iostream>
#include <cstring>
#include <algorithm>
#define seed 31
#define maxn 1000010
#define ull unsigned long long
using namespace std;
char s[maxn];
int n,m,len[maxn],sta[maxn];
ull ub[maxn];
int cal(int x,int y){
  if (x==y) return len[x];
  else {
    int l=0,r=min(len[x],len[y]);
    while (l<r){
        int m=(l+r+1)/2;
        if (ub[sta[x]+m-1]==ub[sta[y]+m-1]) l=m;
        else r=m-1;
    }
    return l;
  }
  return 0;
}
int main (){
  //freopen("test.in","r",stdin);
  int T,t=1;scanf("%d",&T);
  while (T--){
    printf("Case %d:\n",t++);
    scanf("%d",&n);
    int pos=0;
    for (int i=0;i<n;i++){
      scanf("%s",s+pos);
      ub[pos]=s[pos];
      sta[i]=pos;
      len[i]=strlen(s+pos);
      for (int j=pos+1;j<pos+len[i];j++)
        ub[j]=ub[j-1]*seed+s[j];
      pos+=len[i];
    }
    scanf("%d",&m);
    for (int i=0;i<m;i++){
        int a,b;scanf("%d%d",&a,&b);
        printf("%d\n",cal(a-1,b-1));
    }
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值