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 as the right angle point, then the other two vertices must be and (one with the same -coordinate and another with the same -coordinate).
Pairing this and means two times the area of this triangle is . Thus, the total contribution for some is .
To do this for each coordinate, we can store the -values for each and the -values for each . Then, we sort the -values for each and the -values for each , and use prefix sums to compute the distance from all -values and distance from all -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:
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 itertoolsimport bisectMOD = 10**9 + 7with 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!