HDU 4622 Reincarnation(字符串hash,hashMap,区间dp)

8 篇文章 0 订阅
7 篇文章 0 订阅

题目链接
题意:给出一个字符串,问区间的不同子串有几个
首先可以直接预处理出所有长度的字串的hash值,然后用区间dp维护。
区间dp的时候需要记录同一长度下的上一个相同hash值出现的位置,使用STL 的map会超时,所以需要手动写个hashMap,也就是hash加冲突处理。记录相同的hash上一次的位置

//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<set>
#include<map>
#include<string>
#include<cassert>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define fastIO ios::sync_with_stdio(false);cin.tie(0);
#define ll unsigned long long
#define pb push_back
#define gcd __gcd


#define For(i,j,k) for(int i=(j);i<=k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)

typedef vector<ll> vec;
typedef pair<int,int> PI;
const double EPS = 1e-8;
const int maxn = 2e3+100;
const int inf  = 1 << 28;

char str[maxn];
ll pp[maxn],p=237,s[maxn];
int dp[maxn][maxn];

const int N=10007;
struct HashMap{
    int head[N],next[N],tot;
    ll value[N];
    int f[N];
    void init(){
        tot=0;
        memset(head,-1,sizeof(head));
    }
    int insert(ll val,int id){
        int t=val%N;
        for(int i=head[t];~i;i=next[i]){
            if(val==value[i]){
                int tmp=f[i];
                f[i]=id;
                return tmp;
            }
        }
        f[tot]=id;
        value[tot]=val;
        next[tot]=head[t];
        head[t]=tot++;
        return 0;
    }
}H;
int main(){
    pp[0]=1;
    for(int i=1;i<maxn;i++)pp[i]=pp[i-1]*p;

    int T;scanf("%d",&T);
    while(T--){
        scanf("%s",str+1);
        int len=strlen(str+1);
        s[0]=0;
        for(int i=1;i<=len;i++)s[i]=s[i-1]*p+str[i];

        cl(dp,0);
        for(int L=1;L<=len;L++){
            H.init();
            for(int i=1;i+L-1<=len;i++){
                ll t=s[i+L-1]-s[i-1]*pp[L];
                int x=H.insert(t,i);
                dp[i][i+L-1]++;
                dp[x][i+L-1]--;

            }
        }
        for(int i=len;i>=0;i--)
            for(int j=i;j<=len;j++)
                dp[i][j]+=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];


        int q;scanf("%d",&q);
        while(q--){
            int x,y;
            scanf("%d%d",&x,&y);
            printf("%d\n",dp[x][y]);
        }
    }
    return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值