Optimize nested loops for counting the total number of selections
using namespace std;


Don't do this.  We have namespaces for a reason, you know.  And we seem to be missing the necessary Standard Library headers &lt;iostream&gt; and &lt;cstdio&gt;.

    int n, m, i, j, m = 0, sum = 0;


These variable names tell us nothing about what they are used for.  Please use more expressive names.

    cin &gt;&gt; n &gt;&gt; m;


When reading from a stream such as std::cin, it's vital to check that the conversion was successful before using the values.  That could be as simple as
if (!cin) {
    return EXIT_FAILURE;
}


    int *a=new int[n];


Prefer a standard container (e.g. std::vector).

    for (i = 0; i &lt; n; i++) {


If we had a std::vector, we could have avoided hand-coding this loop:
auto a = std::vector{};
a.reserve(n);
std::copy_n(std::istream_iterator&lt;int&gt;(std::cin), n, a.begin());


        scanf(&quot;%d&quot;, &amp;a[i]);


Why are we mixing C++ streams and C stdio?  It's better to use just one (preferably the streams).  Again, we're missing the test whether the conversion was successful.