洛谷-P2292-L语言(字典树)

链接:

https://www.luogu.org/problem/P2292

题意:

标点符号的出现晚于文字的出现,所以以前的语言都是没有标点的。现在你要处理的就是一段没有标点的文章。

一段文章T是由若干小写字母构成。一个单词W也是由若干小写字母构成。一个字典D是若干个单词的集合。我们称一段文章T在某个字典D下是可以被理解的,是指如果文章T可以被分成若干部分,且每一个部分都是字典D中的单词。

例如字典D中包括单词{‘is’, ‘name’, ‘what’, ‘your’},则文章‘whatisyourname’是在字典D下可以被理解的,因为它可以分成4个单词:‘what’, ‘is’, ‘your’, ‘name’,且每个单词都属于字典D,而文章‘whatisyouname’在字典D下不能被理解,但可以在字典D’=D+{‘you’}下被理解。这段文章的一个前缀‘whatis’,也可以在字典D下被理解,而且是在字典D下能够被理解的最长的前缀。

给定一个字典D,你的程序需要判断若干段文章在字典D下是否能够被理解。并给出其在字典D下能够被理解的最长前缀的位置。

思路:

建字典树, 对每个单词在句子上的结束做标记, 说明可以另开一次.

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 1e6+10;

int Pos[MAXN];
struct Trie
{
    int Next[26];
    int end;
    void Init()
    {
        end = 0;
        memset(Next, 0, sizeof(Next));
    }
}trie[MAXN];
int n, m, cnt;

void Insert(string word)
{
    int pos = 0;
    int len = word.length();
    for (int i = 0;i < len;i++)
    {
        if (trie[pos].Next[word[i]-'a'] == 0)
        {
            trie[pos].Next[word[i]-'a'] = ++cnt;
            trie[cnt].Init();
        }
        pos = trie[pos].Next[word[i]-'a'];
    }
    trie[pos].end = 1;
}

int Count(string sen)
{
    int ans = 0, pos = 0;
    memset(Pos, 0, sizeof(Pos));
    int len = sen.length();
    for (int i = 0;i < len;i++)
    {
        if (trie[pos].Next[sen[i]-'a'] == 0)
            break;
        pos = trie[pos].Next[sen[i]-'a'];
        if (trie[pos].end == 1)
            Pos[i] = 1;
    }
    for (int i = 0;i < len;i++)
    {
        if (Pos[i] == 0)
            continue;
        else
            ans = i+1;
        pos = 0;
        for (int j = i+1;j < len;j++)
        {
            if (trie[pos].Next[sen[j]-'a'] == 0)
                break;
            pos = trie[pos].Next[sen[j]-'a'];
            if (trie[pos].end == 1)
                Pos[j] = 1;
        }
    }
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    trie[0].Init();
    for (int i = 1;i <= n;i++)
    {
        string tmp;
        cin >> tmp;
        Insert(tmp);
    }
    for (int i = 1;i <= m;i++)
    {
        string tmp;
        cin >> tmp;
        Count(tmp);
        cout << Count(tmp) << endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/YDDDD/p/11605541.html