hash(2014北京邀请赛)bnu34990

Current Server Time: 2014-09-26 20:01:43

Justice String

2000ms
65536KB
64-bit integer IO format:   %lld       Java class name:   Main
Font Size:    

Given two strings A and B, your task is to find a substring of A called justice string, which has the same length as B, and only has at most two characters different from B.

Input

The first line of the input contains a single integer T, which is the number of test cases.
For each test case, the first line is string A, and the second is string B.
Both string A and B contain lowercase English letters from  a to  z only. And the length of these two strings is between 1 and 100000, inclusive. 
 

Output

For each case, first output the case number as " Case #x: ", and x is the case number. Then output a number indicating the start position of substring C in A, position is counted from 0. If there is no such substring C, output -1.
And if there are multiple solutions, output the smallest one. 

 

Sample Input

3
aaabcd
abee
aaaaaa
aaaaa
aaaaaa
aabbb

Sample Output

Case #1: 2
Case #2: 0
Case #3: -1

Source


想起当时北京邀请赛被虐的是有多么的惨。。。

这个题当时没有搞出来,现在想想还是比较简单的。

思路:hash搞的,枚举A串的起始位置,然后判断当前位置是不是符合条件,判断的时候,相当于根据A,B中不同的字符,把它们分成好多段,找每一段的时候根据hash进行二分找出这一段匹配的长度

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef unsigned long long LL;
const int maxn=100010;
const int B=123;
char s1[maxn],s2[maxn];
LL HA[maxn],HB[maxn],xp[maxn];
int n,m;

void gethash(char *s,LL *H)
{
    int n=strlen(s);
    H[n]=0;
    for(int i=n-1;i>=0;i--)
        H[i]=H[i+1]*B+s[i]-'a';
}
int find(int x,int y)
{
    int l=0,r=m;
    while(l<r)
    {
        int mid=l+(r-l+1)/2;
        LL tmpa=HA[x]-HA[x+mid]*xp[mid];
        LL tmpb=HB[y]-HB[y+mid]*xp[mid];
        if(tmpa==tmpb)l=mid;
        else r=mid-1;
    }
    return  l;
}
bool judge(int pos)
{
    int cnt=0;
    for(int i=pos,j=0;i<n&&j<m-1;i++,j++)
    {
        int len=find(i,j);
        i+=len;
        j+=len;
        cnt++;
        if(cnt>=2&&j<m-1)
        {
            len=find(i+1,j+1);
            j+=len;
            if(j>=m-1)return true;
            else return false;
        }
    }
    return 1;
}
int solve()
{
    n=strlen(s1);
    m=strlen(s2);
    for(int i=0;i<=n-m;i++)
        if(judge(i))return i;
    return -1;
}
int main()
{
    int T,cas=1;
    scanf("%d",&T);
    xp[0]=1;
    for(int i=1;i<maxn;i++)xp[i]=xp[i-1]*B;
    while(T--)
    {
        scanf("%s%s",s1,s2);
        gethash(s1,HA);
        gethash(s2,HB);
        printf("Case #%d: %d\n",cas++,solve());
    }
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值