JZOJ5001. Trie树

28 篇文章 0 订阅

题目大意

给定 n 个字符串,现在可以将这n个字符串分别随便重排。求它们构出的Trie最少的节点数是多少。

Data Constraint
n16

题解

因为希望节点数尽量少,我们每次必然是尽可能地抽出公共部分作为前缀,那么剩下的就可以划分为两个集合处理了。
然后可以状压了,设 f[s] 表示状态为 s 的集合最少需要节点数。转移就是枚举s的一个子集。

时间复杂度: O(3n)

SRC

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std ;

#define N 20 + 10
#define M 70000 + 10
typedef long long ll ;
struct Note {
    int Cnt[N] ;
} W[N] ;

char S[M] ;
int f[M] ;
int n ;

int main() {
    freopen( "trie.in" , "r" , stdin ) ;
    freopen( "trie.out" , "w" , stdout ) ;
    scanf( "%d" , &n ) ;
    for (int i = 1 ; i <= n ; i ++ ) {
        scanf( "%s" , S + 1 ) ;
        int len = strlen( S + 1 ) ;
        for (int j = 1 ; j <= len ; j ++ ) {
            int x = S[j] - 'a' ;
            W[i].Cnt[x] ++ ;
        }
    }
    for (int s = 1 ; s < (1 << n) ; s ++ ) {
        int now = 0 , tot ;
        for (int i = 0 ; i < 26 ; i ++ ) {
            int Minv = 0x7FFFFFFF ;
            tot = 0 ;
            for (int j = 1 ; j <= n ; j ++ ) {
                if ( (s >> (j - 1)) & 1 ) {
                    Minv = min( Minv , W[j].Cnt[i] ) ;
                    tot ++ ;
                }
            }
            now += Minv ;
        }
        if ( tot == 1 ) { f[s] = now ; continue ; }
        f[s] = 0x7FFFFFFF ;
        for (int s1 = s - 1 ; s1 ; s1 = (s1 - 1) & s )
            f[s] = min( f[s] , f[s1] + f[s^s1] - now ) ;
    }
    printf( "%d\n" , f[(1<<n)-1] + 1 ) ;
    return 0 ;
}

以上.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值