All problems

Problem 166

Is Graph Bipartite

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

Problem

You are given an undirected graph with N nodes and M edges. Decide whether it is bipartite: whether its nodes can be split into two groups so that every edge connects a node in one group to a node in the other. The graph may be disconnected, and each part must be checked. Try to colour the nodes with two colours using BFS or DFS: give the start node colour 0, every neighbour the opposite colour, and so on. If an edge ever connects two nodes of the same colour, the graph is not bipartite. A graph is bipartite exactly when it has no cycle of odd length.

Input

First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v.

Output

Print YES or NO.

Constraints

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

Example input

4 4
1 2
2 3
3 4
4 1

Example output

YES

Explanation

The edges form the 4-cycle 1-2-3-4-1. Putting nodes 1 and 3 in one group and 2 and 4 in the other makes every edge cross between the groups, so the answer is YES.

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

Previous: Detect Cycle in an Undirected Graph Next: Smallest Topological Order