POJ1002 题解

看了很多人的解题报告。。发现很多写法

  • 快排
  • 堆排
  • hash
  • 优先队列

但是。。就是没有字典树的。。然后我就写个字典树把。。因为我看到这道题的第一想法是字典树。。然后我WA了5次。。然后。发现是个低级错误导致了我的WA、天坑!
写插入函数的时候。。一开始是写成了这样的。。

for(; *pst++; ) {
        int ch = *pst - '0';
        if( ptr->child[ch] == NULL )
            ptr->child[ch] =  ++pbuf;
        ptr = ptr->child[ch];
    }

然后天坑!!o(︶︿︶)o 唉烦烦烦直接贴代码!

#include <iostream>
#include <cstring>
#include <cstdio>

#define MAX_LEN 777777

using namespace std;

struct tire {
    tire *child[10];
    char str[10];
    int num;
};

const char map[26] = {'2','2','2','3','3','3','4','4','4',
                      '5','5','5','6','6','6','7','7','7',
                      '7','8','8','8','9','9','9'};

tire root[MAX_LEN], *pbuf = root;
bool flag = false;

void ins    (char* s );
void output (tire* rt);
void dispose(char* s );

int main(int argc, char const *argv[])
{
    freopen("input","r",stdin);
    freopen("output","w",stdout);
    int  n;
    char s[200];
    for(scanf("%d\n", &n); n--;){
        gets(s);
        dispose(s);
        ins(s);
    }
    if( flag == true ){
        output(root);
    } else 
        cout << "No duplicates. ";

    return 0;
}

void ins(char *s)
{
    tire* ptr = root;
    char* pst = s;
    for(; *pst; ++pst) {
        int ch = *pst - '0';
        if( ptr->child[ch] == NULL )
            ptr->child[ch] =  ++pbuf;
        ptr = ptr->child[ch];
    }

    strcpy(ptr->str, s);
    ptr->str[3] = '-';
    strcpy(ptr->str+4, s+3);

    if( ++ptr->num > 1 )
        flag = true;
}

void dispose(char *s)
{
    char b[200], *p = s, *pb = b;

    for( ; *p; ++p) {
        if( *p == '-' ) continue;
        if( *p >= 'A' && *p <= 'Z')
            *pb++  = map[*p-'A'];
        else *pb++ = *p;
    }
    *pb = '\0';

    strcpy(s, b);
}

void output(tire *rt)
{
    if( rt ) {
        for (int i = 0; i < 10; ++i){
            output(rt->child[i]);
        }
        if(rt->num > 1) {
            printf("%s %d\n", rt->str, rt->num);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值