UVA - 11488 字典树

 

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2483

题意:给定一堆由0,1组成的串,现在要求一个最大值,值的结果为:串前缀*用于此前缀的字符串个数

思路:字典树,在插入字符串的时候就开始统计,对于插入的每个字符串的前缀的值都累加,然后一边插入一边维护最大值即可。

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <time.h>
using namespace std;
typedef long long int LL;
const int MAXN = 50000 * 200 + 5;
char str[50];
struct Trie{
    int val;
    int child[2];
    Trie(){
        val = 0;
        memset(child, 0, sizeof(child));
    }
}trie[MAXN];
int trieN, ans;
void Insert(char *str){
    int d, x = 0;
    for (int i = 0; str[i]; i++){
        d = str[i] - '0';
        if (trie[x].child[d] == 0){
            trie[x].child[d] = ++trieN;
        }
        x = trie[x].child[d];
        trie[x].val++;
        ans = max(ans, (i + 1)*trie[x].val);
    }
}
void Delete(int u){
    for (int i = 0; i < 2; i++){
        if (trie[u].child[i]){
            Delete(trie[u].child[i]);
        }
    }
    trie[u].val = 0;
    memset(trie[u].child, 0, sizeof(trie[u].child));
}
int main(){
    int t, n;
    scanf("%d", &t);
    while (t--){
        scanf("%d", &n); trieN = 0, ans = 0;
        for (int i = 1; i <= n; i++){
            scanf("%s", str);
            Insert(str);
        }
        printf("%d\n", ans);
        Delete(0);
    }
    return 0;
}

 

posted @ 2016-08-03 11:53  キリト  阅读(199)  评论(0编辑  收藏  举报