You are given a complete graph with nodes. There are two values associated with each node , denoted by and .
The weight of the edge between two nodes and is denoted by .
Find the sum of the square of weights of all the edges. Formally, find the value
Example:
Input: n=3, A[] = { 1, 3, 2 }, B[] = { 2, 3, 3 }
Output: 19
Approach
Java
public class WeightedGraph {public static void main(String[] args) {long mod = (long) 1e9 + 7;int n = 3;long a[] = new long[n];int A[] = { 1, 3, 2 };int B[] = { 2, 3, 3 };for (int i = 0; i < n; ++i)a[i] = A[i] % mod;long ans = 0, saa = 0, sbb = 0, sab = 0;for (int i = 0; i < n; ++i) {long b = B[i] % mod;long aa = a[i] * a[i] % mod;long bb = b * b % mod;long ab = a[i] * b % mod;ans = (ans + (sbb * aa % mod) + (saa * bb) - (2l * sab * ab % mod) + mod) % mod;saa = (saa + aa) % mod;sbb = (sbb + bb) % mod;sab = (sab + ab) % mod;}System.out.println(ans);}}
No comments:
Post a Comment