I doubt. Part of the question requires calculating the sum of the absolute distance of a point from different points. | x - x1 | + | x - x2 | + | x - x3 | + | x - x4 | ....
I need to calculate this distance in O (n) for each point iterating in an array, for example:
array = {3,5,4,7,5}
sum of distance from previous points
dis[0] = 0; dis[1] = |3-5| = 2 dis[2] = |3-4| + |5-4| = 2 dis[3] = |3-7| + |5-7| + |4-7| = 9 dis[4] = |3-5| + |5-5| + |4-5| + |7-5| = 5
Can anyone suggest an algo to do this? An algorithm smaller than O (n ^ 2) will be evaluated (not necessarily O (n)).
Code for O (n ^ 2)
REP(i,n){ LL ans = 0; for(int j=0;j<i;j++) ans= ans + abs(a[i]-a[j]) dis[i]=ans; }
c algorithm graph dynamic-programming distance
akash
source share