This problem can be solved by at least 4 methods:
- Quick Sort
- Binary Search Tree
- Trie and Depth First Search
- Map
Unfortunately, I only implemented the first two methods. Here is the source code:
Use Quick Sort:
``` cpp POJ 2418 Hardwood Species (Use Quick Sort)
#include
Use BST
``` cpp POJ 2418 Hardwood Species (Use Binary Search Tree)
#include <iostream>
#include <algorithm>
using namespace std;
#define N 1000000
char a[N][31];
int b[N];
int c[N];
double d[N];
bool cmp(int x,int y){
int i;
for(i=0;i<31;i++){
if(a[x][i]!=a[y][i]||a[x][i]==0)
break;
}
return a[x][i]<a[y][i];
}
int main(){
//freopen("in.txt","r",stdin);
int n=0;
int i;
while(scanf("%[^\n]",a[n])!=EOF&&a[n][0]){
b[n]=n;
n++;
getchar();
}
sort(b,b+n,cmp);
for(i=0;i<n;i++)
c[i]=1;
for(i=0;i<n-1;i++){
int j1=b[i],j2=b[i+1];
if(strcmp(a[j1],a[j2])==0){
c[j2]+=c[j1];
c[j1]=0;
}
}
for(i=0;i<n;i++){
if(c[i]>0){
d[i]=100.0*c[i]/n;
}
}
for(i=0;i<n;i++){
int j=b[i];
if(c[j]){
printf("%s %.4f\n",a[j],d[j]);
}
}
return 0;
}