Editorial for Sắp xếp số trong xâu (TS10 LQĐ, Đà Nẵng 2016)


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

\(\color{red}{\text{Spoiler Alert}_{{}_{{}^{{}^{v2.0}}}}}\)

\(\color{red}{\text{Khuyến khích bạn đọc trước khi đọc phần lời giải xin hãy thử code ra thuật của mình dù nó có sai hay đúng}}\)

\(\color{red}{\text{Sau đó từ phần bài giải và thuật toán trước đó mà đối chiếu, rút nhận xét với thuật của mình và thu được bài học (không lãng phí thời gian đâu).}}\)



\(\color{orange}{\text{Hint <Implementation>}}\)

  • Lưu vị trí các chữ số của xâu s vào mảng \(pos[]\)

  • Lưu các chữ số của xâu s vào mảng \(val[]\)

  • Sắp xếp mảng \(val[]\) và lần lượt đưa các chữ số ở vị trí \(x\) của mảng \(val[x]\) vào \(s[pos[x]]\)


\(\color{green}{\text{Preference AC Code }}\): Implementation

\(^{^{\color{purple}{\text{Complexity : }} O(|s| \log |s|)\ \color{purple}{\text{time}}\ ||\ O(|s|)\ \color{purple}{\text{memory}}}}\)

C++
bool isDigit(char c) { return '0' <= c && c <= '9'; }
int main()
{
    string s;
    getString(s);

    vector<int> val;
    vector<int> pos;
    for (int i = 0; i < s.size(); ++i)
    {
        if (isDigit(s[i]))
        {
            val.push_back(s[i]);
            pos.push_back(i);
        }
    }

    sort(all(val));
    for (int i = 0; i < pos.size(); ++i)
        s[pos[i]] = val[i];

    cout << s;
    return 0;
}

\(\color{purple}{\text{Question}}\)

  • Bạn có thể giải nó trong thời gian tuyến tính không ? \(O(n) time\) ấy


Comments

There are no comments at the moment.