数据结构实验之查找三:树的种类统计

本文介绍了一种使用C++实现的树种统计方法,能够处理大量数据并快速准确地计算每种树所占的比例。通过利用哈希表记录树的出现频率,并采用优先队列按字典序输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

随着卫星成像技术的应用,自然资源研究机构可以识别每一个棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。

输入

输入一组测试数据。数据的第1行给出一个正整数N (n <= 100000),N表示树的数量;随后N行,每行给出卫星观测到的一棵树的种类名称,树的名称是一个不超过20个字符的字符串,字符串由英文字母和空格组成,不区分大小写。

输出

按字典序输出各种树的种类名称和它占的百分比,中间以空格间隔,小数点后保留两位小数。

示例输入

2
This is an Appletree
this is an appletree

示例输出

this is an appletree 100.00%

提示



要按字典序排的

一开始没看题意的字典序,好尴尬,错了几遍才发现,然后排序这超时了,试了下C++的一些东西,讲真真的好用
<span style="font-family:KaiTi_GB2312;font-size:14px;color:#009900;"><span style="font-family:KaiTi_GB2312;font-size:14px;color:#339999;">#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <queue>
#include<map>
using namespace std;
struct node//保存字符串
{
    char str[30];
    struct node *next;
}p;
int a[100000];
int l,i,n;
char str[30];
map<string,double>mp;//记录字符串出现的次数
struct node *Search(int n)
{
    struct node*head,*tail,*p,*t;
    head=(struct node*)malloc(sizeof(struct node));//初始化
    tail=head;
    head->next=NULL;//初始化
    while(n--)
    {
        gets(str);
        l=strlen(str);
        for(i=0;i<l;i++)
        {
            if(str[i]>='A'&&str[i]<='Z')//全都转化为小写
                str[i]=str[i]+32;
        }
        p=(struct node*)malloc(sizeof(struct node));//插入字符串
        p->next=NULL;
        strcpy(p->str,str);

        t=head->next;
        while(t)
        {
            if(strcmp(t->str,p->str)==0)//相同字符串次数加加
            {
                mp[t->str]++;
                free(p);
                break;
            }
            t=t->next;
        }
        if(t==NULL)//不然加入新元素
        {
            tail->next=p;
            tail=p;
            mp[p->str]=1;
        }
    }
    return (head);返回头指针</span></span>
<span style="font-family:KaiTi_GB2312;font-size:14px;color:#009900;"><span style="font-family:KaiTi_GB2312;font-size:14px;color:#339999;">}

void print(struct node*head)
{
    struct node*p=head->next;
    string c;
    priority_queue<string,vector<string>,greater<string> >q;//最小优先队列
    while(p)
    {
        q.push(p->str);
        p=p->next;
    }
    while(!q.empty())
    {
        c=q.top();
        q.pop();
        cout<<c<<" ";
        printf("%.2lf",mp[c]*100.0/n);
        cout<<"%"<<endl;
    }
}
int main()
{
    struct node*p;
    scanf("%d\n",&n);
    p=Search(n);
    print(p);
    return 0;
}</span><span style="font-family:微软雅黑, 黑体, 宋体, Verdana, Helvetica, Arial, Geneva, sans-serif;color: rgb(51, 51, 51);">
</span></span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值