动物统计加强版
时间限制:3000 ms | 内存限制:150000 KB
难度:4
描述
在美丽大兴安岭原始森林中存在数量繁多的物种,在勘察员带来的各种动物资料中有未统计数量的原始动物的名单。科学家想判断这片森林中哪种动物的数量最多,但是由于数据太过庞大,科学家终于忍受不了,想请聪明如你的ACMer来帮忙。
输入
第一行输入动物名字的数量N (1 <= N <= 4000000 ),接下来的N 行输入N 个字符串表示动物的名字(字符串的长度不超过10 ,字符串全为小写字母,并且只有一组测试数据)。
输出
输出这些动物中最多的动物的名字与数量,并用空格隔开(数据保证最多的动物不会出现两种以上)。
样例输入
10
boar
pig
sheep
gazelle
sheep
sheep
alpaca
alpaca
marmot
mole
样例输出
sheep 3
来源
[陈玉 张云聪]原创
字典树模板题,记录每个单词最后一个节点的个数,不断更新最多的单词的数量。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
#include<string>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#include<set>
#include<map>
#include<cstdio>
#include<limits.h>
#define MOD 1000000007
#define fir first
#define sec second
#define fin freopen("/home/ostreambaba/文档/input.txt", "r", stdin)
#define fout freopen("/home/ostreambaba/文档/output.txt", "w", stdout)
#define mes(x, m) memset(x, m, sizeof(x))
#define Pii pair<int, int>
#define Pll pair<ll, ll>
#define INF 1e9+7
#define Pi 4.0*atan(1.0)
#define lowbit(x) (x&(-x))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-12 ;
const int maxn = 1000010 ;
const int maxm = 200010 ;
using namespace std ;
inline int read(){
int x(0 ),f(1 );
char ch=getchar();
while (ch<'0' ||ch>'9' ) {if (ch=='-' ) f=-1 ;ch=getchar();}
while (ch>='0' &&ch<='9' ) x=x*10 +ch-'0' ,ch=getchar();
return x*f;
}
char res[11 ];
int _max;
struct Trie{
Trie *next[26 ];
int count;
Trie(){
mes(next,0 );
count=0 ;
}
};
Trie *rt;
void insert(char *str){
Trie *cur=rt;
for (const char *p=str;*p;++p){
if (!cur->next[*p-'a' ]){
cur->next[*p-'a' ]=new Trie();
}
cur=cur->next[*p-'a' ];
}
++cur->count;
if (cur->count>_max){
_max=cur->count;
strcpy (res,str);
}
}
int main()
{
int N;
N=read();
char str[11 ];
Trie tree;
rt=new Trie();
_max=0 ;
while (N--){
gets(str);
insert(str);
}
printf ("%s %d\n" ,res,_max);
return 0 ;
}