Sum of squares of distances between all pairs from given points | C ++ program for the above approach ; Function to find the sum of squares of distance between all distinct pairs ; Stores final answer ; Traverse the array ; Adding the effect of this point for all the previous x - points ; Temporarily add the square of x - coordinate ; Add the effect of this point for all the previous y - points ; Print the desired answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSquareSum ( int Coordinates [ ] [ 2 ] , int N ) { long long xq = 0 , yq = 0 ; long long xs = 0 , ys = 0 ; long long res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int a , b ; a = Coordinates [ i ] [ 0 ] ; b = Coordinates [ i ] [ 1 ] ; res += xq ; res -= 2 * xs * a ; res += i * ( long long ) ( a * a ) ; xq += a * a ; xs += a ; res += yq ; res -= 2 * ys * b ; res += i * ( long long ) b * b ; yq += b * b ; ys += b ; } cout << res ; } int main ( ) { int arr [ ] [ 2 ] = { { 1 , 1 } , { -1 , -1 } , { 1 , -1 } , { -1 , 1 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSquareSum ( arr , N ) ; return 0 ; }