河南省第十届省赛 谍报分析

title: 谍报分析 河南省第十届省赛
tags: [省赛]

题目分析:

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

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

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

输入:

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

分析:

这道题关键的一点就是以文件的形式给都进去的,一直读到文件的末尾,其他的也没有啥要注意的啦

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct Node
{
    string str;
    int num;
} node[160];
bool cmp(Node a,Node b)
{
    if(a.num!=b.num)
        return a.num>b.num;
 
    else
        return a.str<b.str;
}
int main()
{
    char ch;
    string st;
    int k=0;
    while(scanf("%c",&ch)!=EOF)///以文件的形式一个一个的读进去
    {
        if(ch>='a'&&ch<='z')///小写字母的话就直接填上
        {
            st+=ch;
        }
        else///其余的一个情况,都以为着当前的单词结束了
        {
            if(st=="")///可能会有连着的不是单词的情况出现
                continue;
            else
            {
                int i;
                for( i=0; i<k; i++)///在结构体中找这个单词有没有出现过
                {
                    if(st==node[i].str)///出现过的话直接把个数加
                    {
                        node[i].num++;
                        break;
                    }
                }
                if(i==k)///没出现过的话,新添进去,个数为1
                {
                    node[k].str=st;
                    node[k].num=1;
                    k++;
                }
                st="";
            }
        }
    }
    sort(node,node+k,cmp);///排序之后输出前10个
    for(int i=0; i<10; i++)
    {
        cout<<node[i].str;
        printf(" %d
",node[i].num);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/cmmdc/p/6887842.html