Wednesday, August 12, 2015

SPOJ Problem BOGGLE

Boggle Scoring

Explanation:


This problem requires simple implementation of a hash, which maps string to number of times different players found it.

Here is the approach.
1. Take a map from string to int (you can use STL). Below are the links provided to learn, if you are not aware.
2. For different words found by multiple players, keep on storing the number of times each word is found, in the above map.
3. For each player, take the word found by him, check if it was also found by some other player. If yes, reject the word, else, calculate the score depending on the length of the word.

C++ Map links.
1. http://www.cplusplus.com/reference/map/map/

Solution:

#include<cstdio>
#include<iostream>
#include<vector>
#include<map>

using namespace std;

vector<string> tokenize(string s, char c){
    //  Splits the string s into vector of words based on character c.
    vector<string> res;
    string tmp = "";
    for(int i=0;i<s.length();i++){
        if(s[i] == c){
            res.push_back(tmp);
            tmp = "";
        }
        else
            tmp.append(1, s[i]);
    }
    res.push_back(tmp);
    return res;
}

long long int findSize(string word){
    //  Returns the score of each word depending on its length.
    if(word.length() <= 4)
        return 1;
    if(word.length() == 5)
        return 2;
    if(word.length() == 6)
        return 3;
    if(word.length() == 7)
        return 5;
    return 11;
}

int main(){

    int n;
    vector< vector<string> > words;
    map<string, int> mymap;
    long long int result = 0;
    string s;

    scanf("%d", &n);
    words.resize(n);
    getline(cin, s);
    for(int i=0;i<n;i++){
        getline(cin, s);
        //  Split the string into different words for ith player.
        words[i] = tokenize(s, ' ');
        //  Increment the count of word found and store in mymap.
        for(int j=0;j<words[i].size();j++){
            mymap[words[i][j]]++;
        }
    }
    //  Traverse through each word found.
    for(int i=0;i<words.size();i++){
        long long int tmpVal = 0;
        for(int j=0;j<words[i].size();j++){
            //  If word not found by anyone else, add the score to ith player's score.
            if(mymap[words[i][j]] == 1)
                tmpVal += findSize(words[i][j]);
        }
        //  Update the maximum score found so far.
        result = max(tmpVal, result);
    }
    printf("%lld", result);
    return 0;
}

Any suggestions are welcome.

No comments:

Post a Comment

SPOJ Problem ONEZERO

Ones and zeros Explanation: A very good problem to practice BFS skills. I think that much hint is good to give the problem a shot. An...