zoukankan      html  css  js  c++  java
  • CSU 1115 最短的名字

    传送门

    Time Limit: 5000MS   Memory Limit: 65536KB   64bit IO Format: %lld & %llu

    Description

    在一个奇怪的村子中,很多人的名字都很长,比如aaaaa, bbb and abababab。
    名字这么长,叫全名显然起来很不方便。所以村民之间一般只叫名字的前缀。比如叫'aaaaa'的时候可以只叫'aaa',因为没有第二个人名字的前三个字母是'aaa'。不过你不能叫'a',因为有两个人的名字都以'a'开头。村里的人都很聪明,他们总是用最短的称呼叫人。输入保证村里不会有一个人的名字是另外一个人名字的前缀(作为推论,任意两个人的名字都不会相同)。
    如果村里的某个人要叫所有人的名字(包括他自己),他一共会说多少个字母?

    Input

    输入第一行为数据组数T (T<=10)。每组数据第一行为一个整数n(1<=n<=1000),即村里的人数。以下n行每行为一个人的名字(仅有小写字母组成)。输入保证一个村里所有人名字的长度之和不超过1,000,000。
     

    Output

    对于每组数据,输出所有人名字的字母总数。

    Sample Input

    1
    3
    aaaaa
    bbb
    abababab 

    Sample Output

      5
    -----------------------------------
    trie,数组不必开到1e6, 题目保证不会有极端case(我MLE了,呵呵)
    ---------------------------------------------------------------------------------------------
     
    #include<bits/stdc++.h>
    using namespace std;
    const int N(5e5+5);
    struct node{
    	int id, dep, nt[26];
    	void init(int _id, int _dep){id=_id, dep=_dep, memset(nt, 0, sizeof(nt));}
    	void renew(){id=0;}
    }trie[N];
    char s[N];
    bool vis[1005];
    void build_trie(int n){
    	int tot=0;
    	trie[tot].init(0, 0); //error-prone
    	for(int id=1; id<=n; id++){
    		cin>>s;
    		for(int i=0, now=0; s[i]; i++){
    			int &nt=trie[now].nt[s[i]-'a'];
    			now=nt?trie[nt].renew(),nt:(trie[++tot].init(id, i+1), nt=tot);
    		}
    	}
    	int res=0;
    	for(int i=0; i<=tot; i++){
    		if(trie[i].id&&!vis[trie[i].id]) res+=trie[i].dep, vis[trie[i].id]=true; 
    	}
    	cout<<res<<endl;
    }
    
    int main(){
    	freopen("in", "r", stdin);
    	int T, n;
    	for(cin>>T; T--; memset(vis, 0, sizeof(vis))){
    		cin>>n;
    		build_trie(n);
    	}
    }
    
  • 相关阅读:
    logback配置模板
    mail
    jpa,querydsl
    加密签名
    angular2快速开始
    主从复制
    随笔
    缺货源的小伙伴们 我发现一个超级好的货源供应链 分享给大家
    canal+kafka+logstash+es 架构 logstash的配置
    golang 根据图片url获取图片尺寸
  • 原文地址:https://www.cnblogs.com/Patt/p/4730660.html
Copyright © 2011-2022 走看看