题意:输入N(0<=N<=1,000,000 )个长度为M(M<=30 )的字符串,字典序输出每种字符串出现个数。
分析:这里采用两种方法,一种是qsort,还有一种BST。
C++源码:
qsort:
const int M = 1000000;
const int N = 36;
char s[M+1][N];
int comp(const void *a, const void *b){
return strcmp((char*)a,(char*)b);
}
int main()
{
int i,j;
char c;
i=j=0;
while((c=getchar())!=EOF){
if(c!='/n')
s[i][j++]=c;
else{
s[i][j]='/0';
i++;
j=0;
}
}
qsort(s,i,sizeof(s[0]),comp);
if(i>1){
int count=1;
char tmp[N];
strcpy(tmp,s[0]);
for(j=1;j<i;j++){
if(!strcmp(s[j],tmp)){
count++;
}else{
printf("%s %.4f/n",tmp,count*100.0/i);
strcpy(tmp,s[j]);
count=1;
}
}
printf("%s %.4f/n", tmp,count*100.0/i);
}
return 0;
}
BST:
const int M = 32;
struct node{
node(char *s):t(1),left(NULL),right(NULL){
strcpy(str,s);
}
char str[M];
int t;
node *left, *right;
};
node* insert(node* r, char *s){
if(r==NULL){
r = new node(s);
}else{
int ans = strcmp(r->str,s);
if(ans == 0)
r->t++;
else if(ans==1)
r->left = insert(r->left,s);
else
r->right = insert(r->right,s);
}
return r;
}
void inorder(node* r,int n){
if(r!=NULL){
inorder(r->left,n);
printf("%s %.4f/n", r->str, r->t*100.0/n);
inorder(r->right,n);
}
}
int main()
{
int num=0;
char s[M];
node* root=NULL;
while(gets(s)!=NULL){
root=insert(root,s);
num++;
}
inorder(root,num);
return 0;
}