Editorial for Đếm cặp


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 1 <Brute-force>}}\)

  • Duyệt từng cặp \((i, j)\) và đếm xem có bao nhiêu cặp thỏa mãn

\(\color{orange}{\text{Hint 2 <STL>::<Map> <Sorting> <Online Solving>}}\)

  • \(a_i + a_j^2 = k \Leftrightarrow a_i = k - a_j^2\)

Tại mỗi vị trí \(j\), ta nhận phần tử và tăng số lần xuất hiện của nó

Sau đó ta tìm \(a_i = k - a_j^2\) và đếm xem \(a_i\) xuất hiện bao nhiêu lần


\(\color{green}{\text{Preference AC Code }}\): STL::map, Sorting, Online Solving

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

C++
int main()
{
    int n, k;
    cin >> n >> k;

    ll res = 0;
    map<int, int> M;
    for (int i = 0; i < n; ++i)
    {
        int x;
        cin >> x;
        M[x]++;
        res += M[k - 1LL * x * x];
    }
    cout << res;
    return 0;
}


Comments

There are no comments at the moment.