代码改变世界

统计单词个数

2019-04-10 14:06  一只弱鸡丶  阅读(197)  评论(0编辑  收藏  举报

题目传送门

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;
#define ll long long
#define re register
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define P pair<int,int>
void read(int &a)
{
    a=0;
    int d=1;
    char ch;
    while(ch=getchar(),ch>'9'||ch<'0')
        if(ch=='-')
            d=-1;
    a=ch-'0';
    while(ch=getchar(),ch>='0'&&ch<='9')
        a=a*10+ch-'0';
    a*=d;
}
void write(int x)
{
    if(x<0)
        putchar(45),x=-x;
    if(x>9)
        write(x/10);
    putchar(x%10+'0');
}
int f[205][25],w[205][205],T;///f[i][j]表示前i字符里面分j段最多的单词数,w[i][j]表示在i——j里面的单词数
char A[205],s[25],word[10][205];
bool judge(int x,int y)
{
    for(re int i=1;i<=T;i++)
    {
        char *p=strstr(&A[x],word[i]);///搜单词表里有没有A[x]开头的字母
        if(p!=NULL&&p-&A[x]==0&&x+strlen(word[i])-1<=y)///p-&A[x]表示可能有A[x]开头的单词,但是这个字母不在&A[x]这个位置
            return 1;
    }
    return 0;
}
int main()
{
    //freopen("in.txt","r",stdin);
    int p,k;
    read(p);
    read(k);
    int len=20*p;
    for(re int i=0;i<p;i++)
    {
        scanf("%s",s);
        strcat(&A[1],s);
    }
    read(T);
    for(re int i=1;i<=T;i++)
        scanf("%s",word[i]);
    for(re int i=len;i>=1;i--)
        for(re int j=i;j>=1;j--)
            if(judge(j,i))
                w[j][i]=w[j+1][i]+1;
            else
                w[j][i]=w[j+1][i];
    for(re int i=1;i<=len;i++)///枚举前i段
        for(re int j=1;j<=k&&j<=i;j++)///枚举分段的个数,最多为k或者i
            for(re int l=j-1;l<i;l++)///前面已分段数-1就是当前开始位置
                f[i][j]=max(f[i][j],f[l][j-1]+w[l+1][i]);
    write(f[len][k]);
    return 0;
}