poj3087(hash)

本文深入探讨了一种基于字符串匹配的算法实现,通过使用哈希函数和动态规划技术,有效地解决了字符串匹配问题。文章详细介绍了算法的设计思路、核心代码实现及性能优化策略。

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

//
// Created by xingchaoyue on 2019/7/27.
//

#include<iostream>
#include<cstdio>
#include<map>
#include<string.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
ull base = 131;
map<ull,ll>mp;
ull a[10010];
char s[10010];
int n,ans = 1;
int prime = 1e9+7;
ull mod = 2123704401301379571l;
ull hashe(char s[]){
    int len = strlen(s);
    ull ans = 0;
    for(int i =0;i<len;++i){
        ans = (ans*base+(ull)s[i])%mod+prime;
    }
    return ans;
}
char s1[1000],s2[1000],s3[1000];
char tmp[1000];

void gettmp(char *tmp,char *s1,char*s2){
    int ps=0;
    for(int i=0;i<n;i++)
    {
        tmp[ps++]=s2[i];
        tmp[ps++]=s1[i];
    }
    tmp[ps]='\0';
}
int main(){
    int t;
    cin>>t;
    int cnt = 1;
    while(t--){
        mp.clear();
        cin>>n;
        scanf("%s%s%s",s1,s2,s3);
        int step = 0;
        while(true){
            gettmp(tmp,s1,s2);
            step++;
            if(!strcmp(tmp,s3)){
                cout<<cnt++<<" "<<step<<endl;
                break;
            }
            else if(mp[hashe(tmp)]&&strcmp(tmp,s3)){
                cout<<cnt++<<" "<<-1<<endl;
                break;
            }
            mp[hashe(tmp)] = 1;
            memcpy(s1,tmp,n);
            memcpy(s2,tmp+n,n);
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值