Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Let's consider the right triangles we can create if we consider every coordinate as the point of the right angle. If we have a point (x,y)\left(x,y\right) as the right angle point, then the other two vertices must be (a,y)\left(a,y\right) and (x,b)\left(x,b\right) (one with the same xx-coordinate and another with the same yy-coordinate).

Pairing this (a,y)\left(a,y\right) and (x,b)\left(x,b\right) means two times the area of this triangle is xayb\left|x-a\right|\cdot\left|y-b\right|. Thus, the total contribution for some (x,y)\left(x,y\right) is (aAxa)(bByb)(\sum_{a∈A}\left|x-a\right|)\cdot(\sum_{b∈B}\left|y-b\right|).

To do this for each coordinate, we can store the yy-values for each xx and the xx-values for each yy. Then, we sort the yy-values for each xx and the xx-values for each yy, and use prefix sums to compute the distance from all xx-values and distance from all yy-values in the lists. For each point, multiply the total horizontal distance and total vertical distance to add that to the total answer.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log N)

C++

#include <bits/stdc++.h>
using namespace std;
void setIO(string prob = "") {
if (!prob.empty()) {
freopen((prob + ".in").c_str(), "r", stdin);
freopen((prob + ".out").c_str(), "w", stdout);
}
}

Java

import java.io.*;
import java.util.*;
public class Triangles {
static class Fence {
int x;
int y;
// terminology: anchor point = vertex of the right angle in a right
// triangle sum of heights of all triangles that use this fence as an
// anchor point

Python

import itertools
import bisect
MOD = 10**9 + 7
with open("triangles.in", "r") as read:
n = int(read.readline())
coordinates = []
x_values = dict()
y_values = dict()

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!