Uva 10126 – Zipf’s Law

This is an easy problem in Uva judge.

http://uva.onlinejudge.org/external/101/10126.html

How I did it:

  • Get n. (Number of occurrences that the problem asks validate)
  • I read line per line
  • I get the words from the read line
  • Put the words int a stl map<string,int>
  • Iterate in the map and if the int is equal to n , print the word.
  • If no word appears n times print “There is no such word.”

Hints:

  • Print a blank line between  cases. The last case doesn’t have a blank line.
  • If no word appears n times print “There is no such word.”
  • The words must be sorted.

Code:

In my github : https://github.com/Fabho/algorithmsSolved/blob/master/10126.cpp

#include <iostream>
#include <cstdio>
#include <cctype>
#include <map>
using namespace std;
map<string,int> myMap;

void getWords(string cad){
string tmp = "";

for(int x=0; x<cad.size(); x++)
   {
     if(isalpha(cad[x]))
        tmp+=tolower(cad[x]);
     else{
           if(tmp.size() > 0)
           {
             myMap[tmp]++;
             tmp = "";
           }

         }

   }
 if(tmp.size() > 0)
    myMap[tmp]++;
 tmp = "";
}

int main(){
int n, casos = 0;
string cad;

while(scanf("%d",&n) != EOF){
    getline(cin,cad);//trash
    while(getline(cin,cad)){
    if(cad == "EndOfText")
       break;
    getWords(cad);
    }
    bool flag = false;

    if(casos == 0)
       casos = 1;
    else
        printf("\n");
    for(map<string,int>::iterator it = myMap.begin(); it != myMap.end(); it++)
    {
        if(it->second == n)
           {
            printf("%s\n", it->first.c_str());
            flag = true;
           }
    }
    if(flag == false)
       printf("There is no such word.\n");
    myMap.clear();
}
return 0;
}

Leave a comment