【河南省第十届ACM 省赛 A-谍报分析】

题目描述

“八一三”淞沪抗战爆发后,*几次准备去上海前线视察和指挥作战。但都因为宁沪之间的铁路和公路遭到了敌军的严密封锁,狂轰滥炸,一直未能成行。

特科组织,其主要任务是保卫的安全,了解和掌握敌方的动向。经过一段时间的监听,谍报组获取了敌方若干份密报,经过分析,发现密文中频繁出现一些单词,情报人员试图从单词出现的次数中,推出敌军的行动计划。

请你编程,快速统计出频率高的前十个单词。

输入

密文是由英语单词(小写字母)组成,有若干段。单词之间由一个或多个空格分开,自然段之后可以用一个“,”或“。”表示结束。整个内容的单词数量不超过10000,不同的单词个数不超过500.

输出

输出占10行,每行一个单词及出现的次数,中间一个空格。要求按频率降序输出,出现次数相同的单词,按字典序输出。

样例输入

shooting is at shanghai station. shooting must 
be carried out. shooting shooting. 
shanghai station must be surrounded, at least a team of one hundred soldiers to fight. twenty five soldiers shooting in the north, twenty five soldiers shooting in the south, twenty five soldiers shooting in the east, twenty five soldiers shooting in the west. 
样例输出

shooting 8 
soldiers 5 
five 4 
in 4 
the 4 
twenty 4 
at 2 
be 2 
must 2 
shanghai 2

 

我的做法是先用map记录每个单词出现的次数,因为map不是顺序结构,没办法sort,所以存到vector<pair<string, int> >中。

每次读一个字符,直到EOF

 

#include <bits/stdc++.h>
using namespace std;
char s[50];
map<string, int>M;
vector<pair<string, int> >V;
bool cmp(pair<string, int>x ,pair<string, int>y)
{
    if(x.second == y.second)
        return x.first < y.first;
    return x.second > y.second;
}
int main()
{
    char c;
    int n = 0, f = 0;
    while(~scanf("%c", &c))
    {
        if(c>='a'&&c<='z'||c>='A'&&c<='Z')
        {
            if(f)
                s[n++] = c;
            else
            {
                s[n++] = c;
                f = 1;
            }
        }
        else
        {
            if(f)
            {
                s[n] = '\0';
                M[s]++;
                n = 0;
                f = 0;
            }
        }
    }
    for(map<string, int>::iterator it = M.begin(); it != M.end(); it++)
        V.push_back(make_pair(it->first, it->second));
    sort(V.begin(), V.end(), cmp);
    int num = 1;
    for(vector<pair<string, int> >::iterator it = V.begin(); it != V.end() && num <= 10; it++, num++)
        cout<<it->first<<" "<<it->second<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/lesroad/p/8811198.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值