Spy Syndrome 2 CodeForces - 633C

本文介绍了一个 CodeForces 上的问题解决方案,利用字典树和深度优先搜索(DFS)来查找并匹配字符串。代码实现了从输入字符串中搜索预存的模式串,并返回所有匹配的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://codeforces.com/problemset/problem/633/C

这里DFS的作用和for循环一样 复杂度有点迷。。

感觉是因为这里用了字典树来剪枝 匹配的要求比较严格 当前位置找不到就必须返回

#include <bits/stdc++.h>
using namespace std;

struct node
{
    node *next[26];
    int id;
    bool flag;
};

node *root;
int ans[10010];
int n,m,flag,num;
char pre[100010][1010];
char tar[10010];

void getnode(node *&ptr)
{
    int i;
    ptr=new node;
    for(i=0;i<26;i++) ptr->next[i]=NULL;
    ptr->flag=false;
}

void update(node *ptr,char *ch,int id,int cur,int len)
{
    if(ptr->next[ch[cur]-'a']==NULL) getnode(ptr->next[ch[cur]-'a']);
    if(cur==len-1)
    {
        ptr->next[ch[cur]-'a']->id=id;
        ptr->next[ch[cur]-'a']->flag=true;
        return;
    }
    update(ptr->next[ch[cur]-'a'],ch,id,cur+1,len);
}

bool dfs(int cur)
{
    node *ptr;
    int i;
    if(cur==n) return true;
    ptr=root;
    for(i=cur;i<n;i++)
    {
        if(ptr->next[tar[i]-'a']==NULL) return false;
        else if(ptr->next[tar[i]-'a']->flag)
        {
            ans[num++]=ptr->next[tar[i]-'a']->id;
            if(dfs(i+1)) return true;
            num--;
        }
        ptr=ptr->next[tar[i]-'a'];
    }
    return false;
}

int main()
{
    int i,j,len;
    char tmp[1010];
    scanf("%d%s",&n,tar);
    getnode(root);
    scanf("%d",&m);
    for(i=0;i<m;i++)
    {
        scanf("%s",pre[i]);
        len=strlen(pre[i]);
        for(j=0;j<len;j++)
        {
            if('A'<=pre[i][len-j-1]&&pre[i][len-j-1]<='Z') tmp[j]=pre[i][len-j-1]+('a'-'A');
            else tmp[j]=pre[i][len-j-1];
        }
        update(root,tmp,i,0,len);
    }
    dfs(0);
    for(i=0;i<num;i++) printf("%s ",pre[ans[i]]);
    printf("\n");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值