动物统计加强版
时间限制:
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
来源
- [陈玉 张云聪]原创 上传者
经典的字典树的问题,代码几乎可以来当模版来用了,就留下来了~~~,不过貌似用运算符重载排序(不知道是不是)也能过。。。。。。。。需要注意的是开辟一个新的内存时下一个指针一定要指向NULL;
字典树代码:
#include<stdio.h> #include<string.h> #include<stdlib.h> int max; char ans[101]; struct node { int count;/*计数器*/ struct node *next[26];/*指向下一个26个字母*/ }; struct node *root;/*建立头节点*/ struct node *newset()/*建立新节点*/ { struct node *p; p=(struct node *)malloc(sizeof(struct node)); for(int i=0;i<26;i++) { p->next[i]=NULL;/*开辟节点*/ } p->count=0;/*计数器初始化为0*/ return p;/*新建完成*/ } void insert(char *s)/*建立字典树*/ { struct node *p; //p=(struct node *)malloc(sizeof(struct node));这里只是需要个指针,再开内存就要超了。。。。。 p=root;/*p开始指向头结点*/ int len=strlen(s); for(int i=0;i<len;i++) { if(p->next[s[i]-'a']==NULL) { p->next[s[i]-'a']=newset();/*建立节点*/ } p=p->next[s[i]-'a']; } p->count++; if(p->count>max) { max=p->count; strcpy(ans,s); } } int main() { int ncases; char str[20]; root=(struct node *)malloc(sizeof(struct node));//newset(); for(int i=0;i<26;i++) { root->next[i]=NULL;/*开辟节点*/ } root->count=0;/*计数器初始化为0*/ scanf("%d",&ncases); while(ncases--) { scanf("%s",str); insert(str); } printf("%s %d\n",ans,max); return 0; }
运算符重载代码:(这个要比sort跟qsort排序要快。。。。。)
(重载运算符提交超时!)#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct tj { char str[11]; int count; }w[4000001]; bool operator<(tj const&x,tj const&y) { if(strcmp(x.str,y.str)<0) return true; return false; } int main() { int n,i,j,p,max; memset(w,0,sizeof(w)); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%s",w[i].str); w[i].count=1; } sort(w,w+n); p=0;max=0; for(i=1;i<n;i++) { if(strcmp(w[i].str,w[i-1].str)==0) { w[i].count=w[i-1].count+1; } if(w[i].count>max) { max=w[i].count; p=i; } } printf("%s %d\n",w[p].str,max); return 0; }
-
第一行输入动物名字的数量N(1<= N <= 4000000),接下来的N行输入N个字符串表示动物的名字(字符串的长度不超过10,字符串全为小写字母,并且只有一组测试数据)。