这道题看例子就能明白是什么意思。唯一坑人的地方就是要纠结如何判断输入结束的标志。看了一下别人的代码,无语了。这道题可以用两道题来写。一种是map,一种是创建排序二叉树。
map写法:
#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
map<string,int> mapTree;
int main() {
double ans=0;
string s;
while(getline(cin,s)) {
//if(s=="end") break;
mapTree[s]++;
ans++;
}
map<string,int>::iterator ite;
for(ite=mapTree.begin(); ite!=mapTree.end();ite++) {
cout<<ite->first;
printf(" %.4f\n",ite->second *100.0/ans);
}
return 0;
}
二叉排序树写法:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct node{
char s[35];
struct node *rc,*lc;
int num;
}nod;
nod *root;
double ans=0;
void insert(char a[]) {
nod *p=root,*q;
if(p==NULL) {
root=(nod *)malloc(sizeof(nod));
strcpy(root->s,a);
root->num=1;
root->lc=NULL;
root->rc=NULL;
return ;
}
int flag=0;
while(p) {
if(strcmp(p->s,a)==0) {
p->num++;
flag=1;
return ;
}
q=p;
p=strcmp(p->s,a)>0 ? p->lc:p->rc;
}
if(flag==0) {
nod *temp=(nod *)malloc(sizeof(nod));
strcpy(temp->s,a);
temp->rc=NULL;
temp->lc=NULL;
temp->num=1;
if(strcmp(q->s,a)>0) q->lc=temp;
else q->rc=temp;
}
}
void print(nod *p) {
if(p!=NULL) {
print(p->lc);
printf("%s %.4f\n",p->s,p->num*100.0/ans);
print(p->rc);
}
}
int main() {
char a[35];
root=NULL;
while(gets(a) &&strcmp(a,"end")) {
insert(a);
ans++;
}
nod *p=root;
print(p);
return 0;
}