All problems

Problem 632

Count Unreachable Pairs of Nodes

Medium · 20 pts · Graph, Union Find, Depth-First Search

Problem

An undirected graph has N nodes numbered from 1 to N. Count the pairs of different nodes {u, v} (unordered) that have no path between them. Find the connected components and their sizes; a node in a component of size s cannot reach the N - s nodes outside it. Summing s × (remaining nodes) while adding the components one by one counts every unreachable pair exactly once. The answer can exceed 2^31.

Input

The first line contains N and M. Each of the next M lines contains an edge u v.

Output

Print the number of unreachable pairs.

Constraints

1 <= N <= 100000; 0 <= M <= 200000

Example input

7 5
1 3
1 5
3 6
2 6
4 7

Example output

10

Explanation

With 7 nodes and edges 1-3, 1-5, 3-6, 2-6 and 4-7, the components are {1, 2, 3, 5, 6} and {4, 7}. Each of the 5 nodes of the first cannot reach either of the 2 nodes of the second, so the answer is 5 × 2 = 10.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Shortest Path in a Grid with Obstacles Elimination Next: Minimum Height Trees