NCPC 2016 B.Bless You Autocorrect!

借鉴自:https://blog.csdn.net/qq_33132383/article/details/78168884

题目来源:https://vjudge.net/problem/Kattis-autocorrect   // CSU OJ 2023

题目意思:给定n个单词存在字典中,只能有打字,退格,确定三个操作,问最小的操作步骤是多少

解题思路: 建立字典树,Bfs跑出节点之间的距离


/*
    之前不明白的地方在于子节点和vector的应用,后来明白 vector记录当前节点所链接的节点
    当发现所链接节点使用的次数只有一次的时候 在这个u的最后压入最后一个字母,即题解图中所给的意思
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>

using namespace std;

const int maxn = 1e6 + 100;

int node[maxn][30], vis[maxn], value[maxn], cnt = 0;
string s;
vector <int> v[maxn];

void inser(string &s) {
    int len = s.length(), u = 0, last;
    for(int i = 0; i < len; i++) {
        int c = s[i] - 'a';
        if(!node[u][c]) {
            node[u][c] = ++cnt; //节点编号
            memset(node[cnt], 0, sizeof(node[cnt]));
            value[cnt] = 0;//节点信息
        }
        value[node[u][c]]++;//子节点的使用次数+1
        v[u].push_back(node[u][c]);
        v[node[u][c]].push_back(u);
        u = node[u][c];
    }
    last = u;
    u = 0;
    for(int i = 0; i < len - 1; i++) {
        int c = node[u][s[i] - 'a'];
        if(value[c] == 1) { //代表着这个节点只被使用过一次
            v[last].push_back(c);
            v[c].push_back(last);  //这一步的反向操作 代表这个子节点直接可以连接到尾部节点
            break;
        }
        u = c; //到下一个节点
    }
}

void Bfs() {
    memset(vis, 0, sizeof(vis));
    queue <int> q;
    q.push(0);
    vis[0] = 1;
    value[0] = 0;
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        for(int i = 0; i < v[u].size(); i++) {
            int c = v[u][i];
            if(!vis[c]) {
                vis[c]  = 1;
                value[c] = value[u] + 1;
                q.push(c);
            }
        }
    }
}

int main() {
//    freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(false);
    int n, m;
    while(cin >> n >> m) {
        cnt = 0;
        for(int i = 0; i < maxn; i++) v[i].clear();
        memset(node,0,sizeof(node));
        memset(value,0,sizeof(value));
        for(int i = 0; i < n; i++) {
            cin >> s;
            inser(s);
        }
        Bfs();
        for(int k = 0; k < m; k++) {
            cin >> s;
            int len = s.length(), u = 0;
            int ans = len;
            for(int p = 0; p < len; p++) {
                int  c = s[p] - 'a';
                if(!node[u][c]) break;
                u = node[u][c];
                ans = min(ans, value[u] + len - 1 - p); //注意是子节点的价值
            }
            cout << ans << endl;
        }
        cout<<endl;
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值