Minimum Spanning Tree of a Grid Graph
Time limit2sMemory limit512 MB
Given an n by m grid of integers, build a graph connecting any two cells in the same row or column with edge weight equal to their absolute difference, and output the MST cost.
- Level
Hard8 of 10
- Topics
- Minimum spanning tree, Greedy, Sorting, Union-find
- Solved
- No attempts yet
Problem
You are given an grid of integers.
Consider the following graph. Each cell of the grid is a vertex. Two cells are connected by an edge if they lie in the same row or the same column, and the cost of that edge equals the absolute difference of the numbers at its endpoints.
Find the cost of the minimum spanning tree of this graph, where the cost of a spanning tree is the sum of the costs of its edges.
Input
The first line contains two integers and , the number of rows and columns of the grid. ()
lines follow. The -th of them contains integers , the elements of the grid. ()
Output
Print a single integer, the cost of the minimum spanning tree.