Transitive Closure

No attempts yetTime limit1sMemory limit128 MB

Problem

You are given a directed graph G=(V,E)G = (V, E). The transitive closure of GG can be represented as a V×V|V| \times |V| matrix RR whose entries are 00 or 11: for two vertices AA and BB, the entry in row AA, column BB is 11 if there is a path from AA to BB, and 00 otherwise.

Because the matrix RR itself can be very large, output only the number of ordered pairs (X,Y)(X, Y) with XYX \ne Y such that a path from XX to YY exists. In other words, count the cells of RR that hold 11 and lie off the diagonal (row \ne column).

A path must use at least one edge, and a vertex returning to itself (X=YX = Y) is never counted.

Input

The first line contains the number of test cases TT (T10T \le 10).

Each test case begins with a line containing the number of vertices NN and the number of edges MM (2N2,5002 \le N \le 2{,}500, 1M10,0001 \le M \le 10{,}000). The next MM lines each contain two integers AA and BB (1A,BN1 \le A, B \le N), meaning there is a directed edge from AA to BB. No edge is given more than once.

Output

For each test case, print on a single line the number of ordered pairs (X,Y)(X, Y) with XYX \ne Y such that a path from XX to YY exists.

Hint

For the first graph of the first test case (N=3N = 3, edges 121 \to 2 and 232 \to 3), the transitive-closure matrix RR of GG is:

0 1 1
0 0 1
0 0 0

Exactly 33 off-diagonal cells (row \ne column) hold 11, so the answer is 33.