LA 3525

LA 3525 - Wild West

 * [Problem Link]

Summary
There are $$M^3$$ gunmen characterized by three different skills, each ranging from 1 to M. A subset containing N of these gunmen are The Bad Guys. We want to select one of the other gunmen to be a Hero. The Hero must beat each of the Bad Guys in at least one skill (not necessarily the same skill for all Bad Guys).

The task is to compute the number of gunmen that can be selected to be the Hero.

Explanation
Consider a Bad Guy with skills [a,b,c]. The set of gunmen that can't beat him is a cuboid with opposite corners [1,1,1] and [a,b,c]. The union U of all these cuboids is exactly the set of gunmen that can't be heroes. Thus the answer is $$M^3$$ minus the volume of U.

We can compute the volume of U in $$O(M \log M)$$ by sweeping in one direction and maintaining the intersection of the sweeping plane and U in some tree-like structure.

Implementations
In C++, STL sets can be used, there is no need to implement the tree-like structure.

Input
3 10 2 8 5 6 3 5 1 3 9 1 3 2 2 2 1 10000 2 2 2 0 0

Output
848 19 999999999992