这是字典树写法,也可用字符串hash
开始因为没开字符数组wa了几发,然后发现前导0没删,然后又发现删前导0的函数写错了,QAQ
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define maxn 15
struct Trie{
Trie * next[maxn];
int v;
};
Trie * root;
int maxnum;
char a[3005][35];
void Init_Trie(){
root = (Trie *)malloc(sizeof(Trie));
for(int i=0;i<maxn;i++){
root -> next[i] = NULL;
}
}
void Add_Trie(char * str){
Trie * p = root , * q;
for(int i=0;str[i]!='\0';i++){
int id = str[i] - '0';
if(p->next[id]==NULL){
q = (Trie *)malloc(sizeof(Trie));
q -> v = 0;
for(int j=0;j<maxn;j++){
q -> next[j] = NULL;
}
p -> next[id] = q;
p = p -> next[id];
}
else {
//p -> next[id]->v++; //记录有某个共同前缀的单词数量
p = p -> next[id];
}
}
p -> v ++;//记录相同单词的数量
if(p->v>maxnum)maxnum = p -> v;
}
int Search_Trie(char * str){
Trie * p = root;
for(int i=0;str[i]!='\0';i++){
int id = str[i] - '0';
p = p -> next[id];
if(p==NULL){
return 0;
}
}
//return p -> v;//返回以搜索串为前缀的数量
return 1;
}
void Del_Trie(Trie * p){
for(int i=0;i<maxn;i++){
if(p->next[i])Del_Trie(p->next[i]);
}
free(p);
}
void Del_Leading_Zero(char * str){
int k = 0;
while(str[k]=='0')k++;
if(k==0)return;
if(k==strlen(str)){
str[1]='\0';
return ;
}
int i;
for(i=k;i<strlen(str);i++){
str[i-k] = str[i];
}
str[i-k] = '\0';
}
void Input(){
int n;
while(~scanf("%d",&n)){
Init_Trie();
maxnum = 0;
for(int i=0;i<n;i++){
scanf("%s",a[i]);
Del_Leading_Zero(a[i]);
//printf("%s\n",a[i]);
Add_Trie(a[i]);
}
printf("%d\n",maxnum);
Del_Trie(root);
}
}
void File(){
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
}
int main(void){
//File();
Input();
return 0;
}