hdu 1800 Flying to the Mars (trie树)

小记:这题其实是比较水的,尤其是数据,看discuss里别人都是用int存的,30位的数int能存的下??!!

思路:trie树来hash,记录每一个值出现的次数,次数最多的就是答案。

这里要注意的就是0, 如果用trie树, 它输入000和00 你必须判断是同一个数0. 或者002和000002.

所以这里要必须去掉前置0,然后再插入

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>

using namespace std;

#define mst(a,b) memset(a,b,sizeof(a))
#define REP(a,b,c) for(int a = b; a < c; ++a)
#define eps 10e-8
#define MAX 10

const int MAX_ = 100010;
const int N = 500000;
const int INF = 0x7fffffff;

char str[MAX_];


typedef struct Node{
    int isStr;
    struct Node *next[MAX];
    Node():isStr(0){
        memset(next, NULL, sizeof(next));
    }
    ~Node(){
        for(int i = 0;i < MAX; ++i)
            if(next[i] != NULL)
                delete next[i];
    }
}TrieNode,*Trie;

Trie root;

int Insert(char *s){
    while(*s == '0')++s;
    TrieNode *p = root;

    while(*s){
        if(p ->next[*s-'0'] == NULL){
            p ->next[*s-'0'] = new TrieNode;
        }
        p = p ->next[*s-'0'];
        s++;
    }
    p->isStr ++;
    return p->isStr;
}

int main() {
    int T, n, m, numa = 0, numb = 0,ans;
    bool flag = 0;
    string s = "";
    while(~scanf("%d", &n)) {
        root = new TrieNode;
        ans = 0;
        REP(i, 0, n) {
            scanf("%s", str);
            m = Insert(str);
            ans = max(ans, m);
        }
        printf("%d\n", ans);

        delete root;
    }
    return 0;
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/ljd4305/article/details/38117869
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞