The advice from @Jamal's answer is sound regarding general programming issues. This is a supplemental answer specifically addressing performance and design issues.
b doesn't need to be an array
'b' in your code need only be a single
long int rather than an array. Your inner loop then becomes
b += abs(num[x] - num[i]);
make only one loop through
You need only iterate through
num at most one time. Instead of reading in each
x and calculating each in a loop, you could instead read all
x values into an array and then calculate all answers in parallel.
It may seem contradictory, but then that means you could make
b back into an array, but one which need only hold
m answers rather than having the dimension
pull loop invariants out of the loop
The chances are good that your compiler will do this for you, but instead of this:
for(i=1; i<x; i++)
You could instead write this:
for(long int i=1, lim=num[x]; i<x; i++)
This assumes that you've also made the change that
b is now a single answers.
generate all answers and then print them
Instead of emitting each answer within your loop, create them all in an array and then emit them all at once at the end of the program. This makes little difference with small amounts of data, but as your data grows larger, this allows more of the relevant pieces to stay in the cache during calculation.
You might even consider creating the output string in memory and then send it to
std::cout, but this only saves very little until the output strings get very large.