http://pat.zju.edu.cn/contests/pat-a-practise/1071
1071. Speech Patterns (25)
People often have a preference among synonyms of the same word. For example, some may prefer "the police", while others may prefer "the cops". Analyzing such patterns can help to narrow down a speaker's identity, which is useful when validating, for example, whether it's still the same person behind an online avatar.
Now given a paragraph of text sampled from someone's speech, can you find the person's most commonly used word?
Input Specification:
Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return '\n'. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].
Output Specification:
For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a "word" is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.
Note that words are case insensitive.
Sample Input:Can1: "Can a can can a can? It can!"Sample Output:
can 5
可以AC的代码:
#include<iostream> #include<cstring> #include<string> #include<ctype.h> #include<map> using namespace std; map<string,int> M; int hash1[1000000]; //经试验 100000会有段错误,说明单词的数量会超多10^5 int main(){ string s; string t; //getchar(); getline(cin,s); getchar();//important int i,j,k,sum,ans; for(i=0;i<1000000;++i){ hash1[i]=0; } int idx=0;//用于记录map中的映射值 int len=s.size(); for(i=0;i<len;++i){ s[i]=tolower(s[i]); //变小写 } i=0; while(i<len){ //分词 sum=0; for(j=i;j<len;++j){ if((s[j]>='a' && s[j]<='z') || (s[j]>='0' && s[j]<='9')){ sum++; } else { break; } } if(sum!=0){ t=s.substr(i,sum); if(M.find(t)==M.end()){//没有找到那么就赋值一个新的映射 M[t]=idx; hash1[idx++]++; } else{ ans=M[t]; hash1[ans]++; } } i=j+1; } ans=0; sum=0; map<string,int>::iterator it; map<string,int>::iterator it1; map<string,int>::iterator it2; for(i=0;i<idx;++i) { if(hash1[i]>sum){ //个数大于 sum=hash1[i]; ans=i; } else { if(hash1[i]==sum) { int flag=0; for(it=M.begin();it!=M.end();++it) { if(it->second==ans){ flag++; it1=it; if(flag==2) break; } if(it->second==i){ flag++; it2=it; if(flag==2) break; } } if(it2->first<it1->first){ ans=i; } } } } for(it=M.begin();it!=M.end();it++){ if(it->second==ans){ break; } } cout<<it->first<<" "<<hash1[ans]<<endl; return 0; }