hdu5510Bazinga

鏈接

點擊跳轉

題解

判斷一個串是否是另一個串的子串用kmpkmp

然後有一個優化就是,如果我在暴力匹配的過程中發現AABB的子串,那麼我可以以後不再匹配AA這個串

因爲一個後面的串假設是CC,我只需要判斷是不是所有前面的串都是CC的子串。如果AA不是CC的子串,那麼BB肯定也不是,所以我完全可以不用去判斷AA

複雜度是這樣的:

因爲我每次第一次匹配失敗就會breakbreak,所以在失配的串上話的時間爲O()O(單個串串長)。而如果匹配成功,就會刪掉一個串,所以匹配成功的串上面花費的總時間是O()O(總串長)

代碼

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 1000010
#define maxe 1000010
#define cl(x) memset(x,0,sizeof(x))
#define rep(i,a,b) for(i=a;i<=b;i++)
#define drep(i,a,b) for(i=a;i>=b;i--)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
    ll c, f(1);
    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
    for(;isdigit(c);c=getchar())x=x*10+c-0x30;
    return f*x;
}
struct KMP  //所有傳進的字符串都要封尾(len+1的位置放一個0)
{
    int n, next[maxn], t[maxn];
    void clear()
    {
        cl(next), n=0;
    }
    void build(int *r, int len)
    {
        int i, j=0;
        n=len;
        for(i=1;i<=len;i++)t[i]=r[i];  t[len+1]=0;
        for(i=2;i<=len;i++)
        {
            for(;j and t[j+1]!=t[i];j=next[j]);
            next[i] = t[j+1]==t[i]?++j:0;
        }
    }
    int move(int pos, int x)
    {
        for(;pos and t[pos+1]!=x;pos=next[pos]);
        return t[pos+1]==x ? pos+1 : 0;
    }
}kmp;
char str[510][2020];
int r[maxn];
int main()
{
    ll T=read(), kase;
    rep(kase,1,T)
    {
        ll n=read(), i, j, k, ans=-1, mx=0;
        vector<ll> len(n+5), die(n+5);
        rep(i,1,n)
        {
            scanf("%s",str[i]+1);
            len[i]=strlen(str[i]+1);
            if(mx>len[i])
            {
                ans=i;
                continue;
            }
            rep(j,1,i-1)
            {
                if(die[j])continue;
                rep(k,1,len[j])r[k]=str[j][k]; r[len[j]+1]='|';
                rep(k,1,len[i])r[len[j]+1+k]=str[i][k];
                kmp.build(r,len[i]+len[j]+1);
                ll t=-1;
                rep(k,1,len[i])t=max(t,(ll)kmp.next[len[j]+1+k]);
                if(t<len[j])break;
                else die[j]=1;
            }
            if(j<=i-1)ans=i;
            mx = max(mx,len[i]);
        }
        printf("Case #%lld: %lld\n",kase,ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章