单词个数(map应用)

Problem A: 单词个数

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 23  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 8
NO ANSWER

首先使用map对象储存单词,并在输入过程中为不同的单词计数

然后将其转存到结构体中,使用结构体进行排序(map对象无法排序,,,,如果可以的话那就是我不会,,,)

然后在判断出现最多的和出现最少的是否唯一

ac代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
typedef struct danci{   //此结构体包含单词,和此单词出现次数 
	string s;
	int num;
}danci; 
bool cmp(danci d1,danci d2){   //按照出现次数排序,若相同则按照字典序 
	if(d2.num==d1.num)return d1.s>d2.s;
	return d1.num>d2.num;
}
int main(){
	map<string,int> m;
	string ss;
	while(1){
		cin>>ss;
		if(ss=="#")break;
		m[ss]++;   //使用map对象储存单词 
	}
	map<string,int>::iterator it;
	danci d[505];
	int h=0;
	for(it=m.begin();it!=m.end();it++){   //将map中元素转存到结构体对象中 
		d[h].s=it->first;
		d[h].num=it->second;
		h++;
	}
	sort(d,d+h,cmp);
	if(h==1)cout<<d[0].s<<endl<<d[0].s<<endl;   //若只有一种单词 
	else {
		if(d[0].num==d[1].num)cout<<"NO ANSWER"<<endl;    //判断出现次数是否唯一 
		else cout<<d[0].s<<" "<<d[0].num<<endl;
		if(d[h-1].num==d[h-2].num)cout<<"NO ANSWER"<<endl;
		else cout<<d[h-1].s<<" "<<d[h-1].num<<endl;
	}
	return 0;
}


版权声明:本文为qq_40788630原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。