Given an array of elements find the largest possible number that can
be formed by using the elements of the array.
eg: 10 9
ans: 910
2 3 5 78
ans: 78532
100 9
ans: 9100
I know this problem has a solution using customized string comparator but i dont understand how it really works.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool compare ( string a, string b )
{
return atoi( (a+b).c_str() ) < atoi((b+a).c_str() );
}
int main()
{
vector<string> vs;
string s;
while ( cin >> s ) {
vs.push_back(s);
}
sort( vs.begin(), vs.end(), compare );
for ( int i = vs.size()-1; i >= 0; i-- ) {
cout << vs[i];
}
}
Can anyone propose an algorithm to solve this problem?
Explanation of the above comparator will be appreciated.
Thank you
Indeed, if we have two strings
SandT, we will most commonly concatenate them in lexicographically reverse order, to make the biggest digits come forward. However, this approach doesn’t perfectly work, when one of these strings is a prefix for the other one.Let
T=SA, i.e.Sis a prefix ofT. We have two choices of concatenation:SSAandSAS. Obviously our choice will depend on which number is bigger:ASorSA.Below is the modification of your code which satisfies this algo: