POJ2001 Shortest Prefixes(Trie树)

传送门

题目大意:对于每一个字符串,求一个它的前缀串,使这个前缀串能够唯一确定这个字符串。空串不能看做前缀。

还是更喜欢这种指针的写法。

code:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const int maxm = 16 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1);
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, -1, -1, -1, 1, 1, 1, 1, -1};
char ch[1009][30];
typedef struct Node
{
    int val;
    Node *next[maxm];
} Trie;
string ans;
void insert(Trie *root, char *s)
{
    int n = strlen(s);
    Trie *p = root;
    for (int i = 0; i < n; i++)
    {
        if (p->next[s[i] - 'a'] == NULL)
        {
            Trie *node = new Trie;
            node->val = 0;
            for (int j = 0; j < maxm; j++)
                node->next[j] = NULL;
            p->next[s[i] - 'a'] = node;
        }
        p = p->next[s[i] - 'a'];
        p->val++;
    }
    return;
}
string query(Trie *root, char *s)
{
    Trie *p = root;
    int n = strlen(s);
    for (int i = 0; i < n; i++)
    {
        p = p->next[s[i] - 'a'];
        ans += s[i];
        if (p->val == 1)
            break;
    }
    return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    int i = 0;
    while (cin >> ch[i])
        i++;
    int cnt = i;
    Trie *root = new Trie;
    root->val = 0;
    for (int i = 0; i < maxm; i++)
        root->next[i] = NULL;
    for (int i = 0; i < cnt; i++)
    {
        char s[30];
        strcpy(s, ch[i]);
        insert(root, s);
    }
    for (int i = 0; i < cnt; i++)
    {
        char s[30];
        strcpy(s, ch[i]);
        ans = "";
        cout << s << " " << query(root, s) << "\n";
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值