#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool is_anagram(string a, string b)
{
sort(a.begin(), a.end());
sort(b.begin(), b.end());
return a == b;
}
int main()
{
vector< vector<string> > list;
const int array_size = 6;
string array[array_size] = { "seaside", "scent", "postman", "disease", "cents", "tampons" };
// Store strings.
bool match;
for (int i = 0; i < array_size; ++i)
{
match = false;
for (int j = 0; !match && j < list.size(); ++j)
{
if (is_anagram(array[i], list[j][0]))
{
list[j].push_back(array[i]);
match = true;
}
}
if (!match)
{
vector<string> t;
list.push_back(t);
list[list.size() - 1].push_back(array[i]);
}
}
// Sort columns.
for (int i = 0; i < list.size(); i++)
{
sort(list[i].begin(), list[i].end());
}
// Sort rows.
sort(list.begin(), list.end(), [](vector<string> a, vector<string> b)
{
return a[0] < b[0];
});
// Display vector.
for (int i = 0; i < list.size(); i++)
{
for (int j = 0; j < list[i].size(); j++)
{
cout << list[i][j] << ' ';
}
cout << endl;
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8YWxnb3JpdGhtPgojaW5jbHVkZSA8dmVjdG9yPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmJvb2wgaXNfYW5hZ3JhbShzdHJpbmcgYSwgc3RyaW5nIGIpCnsKICAgIHNvcnQoYS5iZWdpbigpLCBhLmVuZCgpKTsKICAgIHNvcnQoYi5iZWdpbigpLCBiLmVuZCgpKTsKICAgIHJldHVybiBhID09IGI7Cn0KCmludCBtYWluKCkKewogICAgdmVjdG9yPCB2ZWN0b3I8c3RyaW5nPiA+IGxpc3Q7CiAgICBjb25zdCBpbnQgYXJyYXlfc2l6ZSA9IDY7CiAgICBzdHJpbmcgYXJyYXlbYXJyYXlfc2l6ZV0gPSB7ICJzZWFzaWRlIiwgInNjZW50IiwgInBvc3RtYW4iLCAiZGlzZWFzZSIsICJjZW50cyIsICJ0YW1wb25zIiB9OwoKICAgIC8vIFN0b3JlIHN0cmluZ3MuCgogICAgYm9vbCBtYXRjaDsKCiAgICBmb3IgKGludCBpID0gMDsgaSA8IGFycmF5X3NpemU7ICsraSkKICAgIHsKICAgICAgICBtYXRjaCA9IGZhbHNlOwoKICAgICAgICBmb3IgKGludCBqID0gMDsgIW1hdGNoICYmIGogPCBsaXN0LnNpemUoKTsgKytqKQogICAgICAgIHsKICAgICAgICAgICAgaWYgKGlzX2FuYWdyYW0oYXJyYXlbaV0sIGxpc3Rbal1bMF0pKQogICAgICAgICAgICB7CiAgICAgICAgICAgICAgICBsaXN0W2pdLnB1c2hfYmFjayhhcnJheVtpXSk7CiAgICAgICAgICAgICAgICBtYXRjaCA9IHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIGlmICghbWF0Y2gpCiAgICAgICAgewogICAgICAgICAgICB2ZWN0b3I8c3RyaW5nPiB0OwogICAgICAgICAgICBsaXN0LnB1c2hfYmFjayh0KTsKICAgICAgICAgICAgbGlzdFtsaXN0LnNpemUoKSAtIDFdLnB1c2hfYmFjayhhcnJheVtpXSk7CiAgICAgICAgfQogICAgfQoKICAgIC8vIFNvcnQgY29sdW1ucy4KCiAgICBmb3IgKGludCBpID0gMDsgaSA8IGxpc3Quc2l6ZSgpOyBpKyspCiAgICB7CiAgICAgICAgc29ydChsaXN0W2ldLmJlZ2luKCksIGxpc3RbaV0uZW5kKCkpOwogICAgfQoKICAgIC8vIFNvcnQgcm93cy4KCiAgICBzb3J0KGxpc3QuYmVnaW4oKSwgbGlzdC5lbmQoKSwgW10odmVjdG9yPHN0cmluZz4gYSwgdmVjdG9yPHN0cmluZz4gYikKICAgIHsKICAgICAgICByZXR1cm4gYVswXSA8IGJbMF07CiAgICB9KTsKCiAgICAvLyBEaXNwbGF5IHZlY3Rvci4KCiAgICBmb3IgKGludCBpID0gMDsgaSA8IGxpc3Quc2l6ZSgpOyBpKyspCiAgICB7CiAgICAgICAgZm9yIChpbnQgaiA9IDA7IGogPCBsaXN0W2ldLnNpemUoKTsgaisrKQogICAgICAgIHsKICAgICAgICAgICAgY291dCA8PCBsaXN0W2ldW2pdIDw8ICcgJzsKICAgICAgICB9CgogICAgICAgIGNvdXQgPDwgZW5kbDsKICAgIH0KCiAgICByZXR1cm4gMDsKfQ==