您的位置:首页 > 其它

hash(2014北京邀请赛)bnu34990

2014-09-26 20:01 351 查看
Current Server Time: 2014-09-26 20:01:43


Justice String

Time Limit: 2000ms
Memory Limit: 65536KB

64-bit integer IO format: %lld Java class name: Main

Prev Submit Status Statistics Discuss Next

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

2014
ACM-ICPC Beijing Invitational Programming Contest

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

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

思路: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
=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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: