题解 P1470 【最长前缀 Longest Prefix】

· · 题解

map大法好

#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
using namespace std;
string S;
int L,F[200005];
map<string,bool> M;
void Init(){
    string s;
    while(cin>>s&&s!=".")
        M[s]=true;
    while(cin>>s)
        S+=s;
    L=S.length();
}
void DP(){
    int i=1,j;
    while(!M[S.substr(0,i)]&&i<=L)
        i++;
    if(i>L){
        printf("0\n");
        return;
    }
    F[i-1]=true;
    for(;i<L;i++)
        for(j=i-1;j>=max(0,i-10);j--)
            if(F[j]&&M[S.substr(j+1,i-j)]){
                F[i]=true;
                break;
            }
    for(i=L-1;i>=0;i--)
        if(F[i]){
            printf("%d\n",i+1);
            return;
        }
}
int main(){
    Init();
    DP();
    return 0;
}