1481: 单词个数
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 21 Solved: 4
[ Submit][ Status][ Web Board]
Description
有一篇文章,请你统计出出现频次最高的单词和最低的单词。如果最高词或最低词不唯一,则用NO ANSWER代替
Input
输入一篇文章, 长度不超过10000字符。 单词之间用空格或换行隔开,除大小写字母和空格换行外不包含其他字符. 不同的单词个数不超过500.
Output
输出两行,第一行为出现频次最高单词,若不唯一则输出”NO ANSWER”,不包含双引号。第二行为出现频次最低单词,若不唯一则输出”NO ANSWER”,不包含双引号。
Sample Input
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
Sample Output
shooting
NO ANSWER
使用到了map,但是map只有按照键排序,并没办法按照值排序,所以需要用到vector,使用pair创建特殊的数据类型,并且创建按照值排序的排序方式
代码如下
#include<algorithm>
#include<map>
#include<vector>
#include<iostream>
#include<cstdio>
using namespace std;
char s[10002];
map<string,int>m;
vector<pair<string,int> >v;//pair可以用来自己构造一种键值对数据类型
bool cmp(pair<string,int>x,pair<string,int>y)//自定义排序时,定义排序规则
{
return x.second > y.second;//若果数量不同,数量大的靠前
}
bool cmp1(pair<string,int>x,pair<string,int>y)//自定义排序时,定义排序规则
{
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);
int k2=0;
string str1;
for(vector<pair<string, int> >::iterator it=v.begin();it!=v.end()&&num<=2;it++,num++)
{
if(num==1){
k2=it->second;
str1=it->first;
}
else{
if(k2==it->second)
{
cout<<"NO ANSWER"<<endl;
k2=-1;
}
else
{
cout<<(--it)->first<<endl;
k2=-1;
}
}
}
if(k2!=-1)
cout<<str1<<endl;
num=1;
k2=0;
sort(v.begin(),v.end(),cmp1);
for(vector<pair<string, int> >::iterator it=v.begin();it!=v.end()&&num<=2;it++,num++)
{
if(num==1){
k2=it->second;
str1=it->first;
}
else{
if(k2==it->second)
{
cout<<"NO ANSWER"<<endl;
k2=-1;
}
else{
cout<<(--it)->first<<endl;
k2=-1;
}
}
}
if(k2!=-1)
cout<<str1<<endl;
return 0;
}