Harvard linguistics professor George Kingsley Zipf (1902-1950) observed that the frequency of the kth most common Word in a text is roughly proportional to 1/k. He justified his observations in a book titled Human behavior and the principle of least effort published in 1949. While Zipf's rationale has largely been discredited, the principle still holds, and others have afforded it a more sound mathematical basis.
Input consists of several test cases. The first line of each case contains a single positive integer n. Several lines of text follow which will contain no more than 10000 words. The text for each case is terminated by a single line containing EndOfText. EndOfText does not appear elsewhere in the input and is not considered a word.
For each test case, output the words which occur n times in the input text, one word per line, lower case, in alphabetical order. If there are no such words in input, output the following line:
There is no such word.Leave a blank line between cases.Sample Input
2In practice, the difference between theory and practice is alwaysgreater than the difference between theory and practice in theory.- AnonymousMan will occasionally stumble over the truth, but most of thetime he will pick himself up and continue on.- W. S. L. ChurchillEndOfTextSample Output
betweendifferenceinwill【解析】這道題就是輸入一個n和一段文本,在輸入到EndOfText表示此段文本輸入結(jié)束,然后判斷輸入的這段文本當(dāng)中有哪些單詞出現(xiàn)了兩次。所以我們其實可以用map<string,int>來做,進(jìn)行統(tǒng)計就好了,而且這個就是按照字典序來排序下去的。所以我們統(tǒng)計完直接遍歷就可以了,這里需要擁有stringsteam來進(jìn)行拆解除每一個單詞。#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<map>#include<sstream>#include<algorithm>using namespace std;map<string,int>a;int main(){ int n,flag=0,i,flag1; string s; while(~scanf("%d",&n)) { a.clear(); if(flag==0) { flag=1;//在第2次以及以后的輸入n之后都要先輸出一個空行 } else if(flag==1) { printf("/n"); } while(getline(cin,s))//逐行讀取 { if(s=="EndOfText") break; else { for(i=0;i<s.size();i++) { if(isalpha(s[i])) s[i]=tolower(s[i]); else s[i]=' ';/*這里一定要注意不是字母的就一定要變成空格 不然其他字符出現(xiàn)了n次也會輸出*/ } } stringstream s1(s); string s2; while(s1>>s2)//以空格為邊界 { a[s2]++; } } flag1=0;//標(biāo)記有沒有出現(xiàn)過n次的單詞 for(map<string,int>::iterator it=a.begin();it!=a.end();it++) { if(it->second==n) { flag1=1; cout<<it->first<<endl; } } if(flag1==0) printf("There is no such word./n");//表示沒有這樣的單詞 } return 0;}
新聞熱點
疑難解答