CodeForces 1003 F - Abbreviation(暴力+kmp)

Problem:

传送门

Solution:

直接暴力枚举每个区间,然后kmp找这个区间出现的次数.

Ac_Code:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define fir first
#define sec second
using namespace std;

map<string,int> s;

int cnt,n;
int a[5500];
int sz[5500];
int nex[5500];
int len;

int main() {
    cin>>n;
    for(int i=0;i<n;i++) {
        string ss;
        cin>>ss;
        if(s[ss] == 0) s[ss] = ++cnt,sz[cnt] = ss.size();
        a[i] = s[ss];
        len += ss.size();
    }
    len += n-1;
    int res = len;
    for(int i=0;i<n;i++) {
        int del = 0;
        for(int j=1; ;j++) {
            del += sz[a[i+j-1]];
            if(j != 1) del++;
            if(i+j-1>=n) break;
            int k = -1,l = 0;
            nex[l] = -1;
            while(l<j) {
                if(k==-1 || a[k+i] == a[l+i]) {
                    k++;
                    l++;
                    nex[l] = k;
                }
                else k = nex[k];
            }
            nex[j] = 0;
            int ans = 0;
            k = i+j,l=0;
            while(k<n) {
                if((l == -1 || a[k] == a[l+i])) {
                    l++;k++;
                    if(l==j) ans++,l = nex[l];
                }
                else l = nex[l];
            }
            if(ans != 0) res = min(res,len-(del-j)*(ans+1));
        }
    }
    cout<<res<<endl;
    return 0;
}

你可能感兴趣的:(CF200题计划)