[URI Online Judge] – 1244 – Sort by Length

Create a program to sort a set of strings by their size. Its program is to receive a set of strings and return by this same size ordered set of words, if the size of the strings are equal, must maintain the original order of the set.

Input

The first line of input has a unique integer N that indicates the number of sets of strings, each set may contain between 1 and 50 inclusive elements, and each of the strings of the set may contain between 1 and 50 inclusive characters.

Output

The output should contain the set of input strings ordered by the length of strings.A blank space must be printed between two words.

Sample Input Sample Output
4
Top Coder comp Wedn at midnight
one three five
I love Cpp
sj a sa df r e w f d s a v c x z sd fd
midnight Coder comp Wedn Top at
three five one
love Cpp I
sj sa df sd fd a r e w f d s a v c x z

My solution:


#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <algorithm>

using namespace std;

struct Pair {
string first;
unsigned int second;
};

bool compare(Pair i, Pair j){
if (i.first.length() == j.first.length())
return i.second < j.second;
return i.first.length() > j.first.length();
}

int main(){
int n;
string s;

cin >> n;
getline(cin, s);
while (n--){
getline(cin, s);
istringstream is(s);
vector<string> raw_strings(istream_iterator<string>{is}, istream_iterator<string>{});

vector<Pair> strings;

for (unsigned int i = 0; i < raw_strings.size(); i++){
strings.push_back({raw_strings.at(i), i});
}

sort(strings.begin(), strings.end(), compare);

for (unsigned int i = 0; i < strings.size(); i++){
cout << strings.at(i).first;
if (i < strings.size() - 1) cout << " ";
}
cout << endl;
}

return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s