Wednesday, September 10, 2014

UVa Problem 483 - Word Scramble

Problem;

Please find the problem here.

Solution:

Initially I thought I would read in the whole line and then reverse the tokens, but it doesn't work great because the last line could either end without an end line character or not, which I cannot tell with the getline function.

So instead I read the characters one-by-one. If I see a non white space character, I accumulate it in a vector, and then when I see a white space character, I flush the previously accumulated characters in reverse order, and then output that white space character. That's all.

Code:

#include "stdafx.h"

// http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=424

#include "UVa483.h"

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int UVa483()
{
    vector<char> charSeen;
    while (true)
    {
        char c = cin.get();
        if (c == ' ' || c == '\r' || c == '\n' || c == -1)
        {
            for (vector<char>::reverse_iterator p = charSeen.rbegin(); p != charSeen.rend(); p++)
            {
                cout << (*p);
            }
            charSeen.clear();
            if (c != -1)
            {
                cout << c;
            }
            else
            {
                break;
            }
        }
        else
        {
            charSeen.push_back(c);
        }
    }

    return 0;
}

No comments :

Post a Comment