Xenny and Partially Sorted Strings

Xenny had a list of N strings of equal length. He wanted to sort them by the first M characters only. That means, while sorting the list of strings, he only wanted to consider the first M characters of each string.

Help Xenny to find out the Kth string in the list after he sorts them.

Note: Xenny wanted to perform stable sorting.
Stable sorting algorithms maintain the relative order of records with equal keys (i.e. values). That is, a sorting algorithm is stable if whenever there are two records R and S with the same key and with R appearing before S in the original list, R will appear before S in the sorted list.

Example:

Input:  n = 3, k = 1, m = 3, s = {"abcdef","abcaaa","aabaaa"}
Output: aabaaa

Approach

C++

#include <bits/stdc++.h>
using namespace std;
typedef pair<stringintpi;

string partialSortedString(int nint k,
                           int mvector<string&s)
{
    priority_queue<pivector<pi>, greater<pi>> q;
    for (int i = 0i < ni++)
    {
        if (s[i].size() == m)
            q.push({s[i]i + 1});
        else if (s[i].size() != m)
        {
            string str = "";
            string p = s[i];
            for (int j = 0j < mj++)
                str += p[j];
            q.push({stri + 1});
        }
    }
    int cnt = 0j = 0;
    while (!q.empty())
    {
        pair<stringintp1 = q.top();
        q.pop();
        cnt++;
        if (cnt == k)
        {
            j = p1.second;
            break;
        }
    }
    return s[j - 1];
}
int main()
{

    int n = 3k = 1m = 3;

    vector<strings = {"abcdef",
                        "abcaaa",
                        "aabaaa"};

    cout << partialSortedString(nkms<< "\n";

    return 0;
}


No comments:

Post a Comment