题目描述
“八一三”淞沪抗战爆发后,***几次准备去上海前线视察和指挥作战。但都因为宁沪之间的铁路和公路遭到了敌军的严密封锁,狂轰滥炸,一直未能成行。
***特科组织,其主要任务是保卫***的安全,了解和掌握敌方的动向。经过一段时间的监听,谍报组获取了敌方若干份密报,经过分析,发现密文中频繁出现一些单词,情报人员试图从单词出现的次数中,推出敌军的行动计划。
请你编程,快速统计出频率高的前十个单词。
输入
密文是由英语单词(小写字母)组成,有若干段。单词之间由一个或多个空格分开,自然段之后可以用一个“,”或“。”表示结束。整个内容的单词数量不超过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<algorithm>
#include<map>
#include<vector>
#include<iostream>
#include<cstdio>
using namespace std;
char s[52];
map<string,int>m;
vector<pair<string,int> >v;//pair可以用来自己构造一种键值对数据类型
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,num=1;
while(scanf("%c",&c)!=EOF)//按照一个个字符一个字符输入,直至文件结束
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z'){
f=1;
s[n++]=c;
}
else{
if(f==1){//判断f是否等于一很重要,等于代表着此时s不为空
s[n]='\0';
m[s]++;//加入到map中
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));//push_back()函数可以在vector,list,set,map等容器中尾部插入数据
//make_pair()函数用来构造pair对应的参数对象
sort(v.begin(),v.end(),cmp);
for(vector<pair<string, int> >::iterator it=v.begin();it!=v.end()&&num<=10;it++,num++)
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}