Count the candidate intervals [L, R] in which all M daughters can each marry a distinct candidate they accept.
Hard8GraphTwo pointersNo attempts yetTime limit2sMemory limit256 MBLong ago, in a country far away, a wise king had M beautiful daughters. The time for them to marry finally came. The king sent word to N neighboring kingdoms, and every kingdom sent one prince to marry a princess.
The king respected his daughters' wishes. He lined the candidates up, numbered them 1 to N from the left, and asked each daughter which of these candidates she was willing to marry.
The king knew mathematics well, so deciding whether every daughter could be given a husband while every wish is respected was easy for him. Then he thought of a more interesting question: how many pairs (L,R) (1≤L≤R≤N) are there such that every daughter can be given a husband using only the candidates numbered L to R?
A candidate marries at most one daughter, and a daughter marries only a candidate she said she was willing to marry. Write a program that answers the king's question.
The first line contains the integers N, M, and K: the number of candidates, the number of daughters, and the number of lines describing the daughters' preferences. (1≤N≤30000, 1≤M≤2000, 1≤K≤min(N×M,100000))
Each of the next K lines contains the integers Ai and Bi, meaning that daughter Bi is willing to marry candidate Ai. (1≤Ai≤N, 1≤Bi≤M) All pairs are different.
Print the number of pairs (L,R) that satisfy the condition.
In the first example the pairs (1,3), (1,4), (1,5), and (2,5) satisfy the condition.