CodeForces - 633C Spy Syndrome 2 —— 字典树+dfs

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lngxling/article/details/82911407

题意:

问一个字符串能否由一些单词反转,再转为小写后构成

思路:

用字典树记录每个字符串,然后dfs进行搜索

字典树要先向后取值再判断能否形成单词..好久不写手都生了

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
#define ll long long
#define max_ 100010
#define mod 1000000007
#define inf 0x3f3f3f3f
int n,m;
char s[10010];
int tree[1000010][27];//静态字典树
int mark[1000010];//记录每个形成单词的位置
int tot=0;//总共用了的树
char tmp[100100][1010];
int ans[100100];
int cnt=0;
void insert(int id)
{
    int now=0;
    for(int i=strlen(tmp[id])-1;i>=0;i--)
    {
        int to;
        if(tmp[id][i]>='a')
        to=tmp[id][i]-'a';
        else
        to=tmp[id][i]-'A';
        if(!tree[now][to])
        tree[now][to]=++tot;
        now=tree[now][to];
    }
    mark[now]=id;
}
int f=0;
bool dfs(int x)
{
    if(x==n)
    {
        return true;
    }
    int now=0;
    for(int i=x;i<n;i++)
    {
        int to=s[i]-'a';
        if(tree[now][to])
        {
            now=tree[now][to];
        }
        else
        return false;
        if(mark[now])
        {
            ans[cnt++]=mark[now];
            if(dfs(i+1))
            return true;
            cnt--;
        }
    }
}
int main(int argc, char const *argv[]) {
    scanf("%d",&n);
    scanf("%s",s);
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%s",tmp[i]);
        insert(i);
    }
    dfs(0);
    for(int i=0;i<cnt;i++)
    printf("%s%c",tmp[ans[i]]," \n"[i==cnt-1]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Lngxling/article/details/82911407