數據結構實驗之查找三:樹的種類統計
Time Limit: 400MS Memory Limit: 65536KB
Problem Description
隨着衛星成像技術的應用,自然資源研究機構可以識別每一個棵樹的種類。請編寫程序幫助研究人員統計每種樹的數量,計算每種樹佔總數的百分比。
Input
輸入一組測試數據。數據的第1行給出一個正整數N (n <= 100000),N表示樹的數量;隨後N行,每行給出衛星觀測到的一棵樹的種類名稱,樹的名稱是一個不超過20個字符的字符串,字符串由英文字母和空格組成,不區分大小寫。
Output
按字典序輸出各種樹的種類名稱和它佔的百分比,中間以空格間隔,小數點後保留兩位小數。
Example Input
2 This is an Appletree this is an appletree
Example Output
this is an appletree 100.00%
//代碼;
//注意的問題1:數字後面如果要輸入字符,記得加getchar();
// 2:把一個字符串賦給另一個字符串,最好用strcmp函數,如果挨個字符賦值的話。記得要把最後的‘\0’也賦進去
// 3:如果要輸出%,可以這樣寫%%;
//再來說說這個題的思路,反正我是沒想到這麼做。沒想到用二叉樹解決問題這麼簡單。應該多方面想想問題,腦洞大一點。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct BiTNode
{
char s[40];
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Creat(BiTree root,char tree[],int n)
{
int i;
if(!root)
{
root = (BiTree)malloc(sizeof(BiTNode));
for(i = 0;i<=n;i++)//賦值,用n把'\0'賦值進去。或者用strcpy函數、
root->s[i] = tree[i];
root->lchild=NULL;//記得讓左孩子和右孩子爲空。否則會運行錯誤。
root->rchild=NULL;
root->data = 1;
}
else
{
if(strcmp(tree,root->s)==0)
{
root->data++;
}
else if(strcmp(tree,root->s)>0)
{
root->rchild = Creat(root->rchild,tree,n);
}
else
root->lchild = Creat(root->lchild,tree,n);
}
return root;
}
void midprint(BiTree root,int n)
{
if(root)
{
midprint(root->lchild,n);
printf("%s %.2lf%%\n",root->s,root->data*1.0/n*100);//注意%輸出
midprint(root->rchild,n);
}
}
int main()
{
int n;
scanf("%d",&n);
int m = n;
getchar();
BiTree root = NULL;
while(n--)
{
int i;
char tree[40];
gets(tree);
int b = strlen(tree);
for(i = 0;i<=b-1;i++)
{
if(tree[i]>='A'&&tree[i]<='Z')
tree[i] = tree[i]+ ('a'-'A');
}
root = Creat(root,tree,b);
}
midprint(root,m);
printf("\n");
return 0;
}