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

题意:

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

思路:

用字典树记录每个字符串,然后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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值