Under construction

Still being built. Things may change

MST and Rectangles

Time limit8sMemory limit1024 MB

Summary
Given an N by N matrix updated by Q rectangle additions (mirrored across the diagonal), find the MST cost of the complete graph with edge weights A[i][j].
Level

Hard8 of 10

Topics
Minimum spanning tree, Prefix sum, Union-find
Solved
No attempts yet

Problem

You have a 2D array AA of size N×NN \times N. Each cell initially contains 0.

You are also given QQ queries of the form X1X_1 X2X_2 Y1Y_1 Y2Y_2 WW, which means you should perform the following operation on AA:

  • For each pair of integers (i,j)(i, j) where X1≤X2<Y1≤Y2X_1 \le X_2 < Y_1 \le Y_2, X1≤i≤X2X_1 \le i \le X_2, and Y1≤j≤Y2Y_1 \le j \le Y_2, add WW to the values of cells A[i][j]A[i][j] and A[j][i]A[j][i].

Consider an undirected graph GG with NN vertices. For each 1≤i,j≤N1 \le i, j \le N, there is an edge connecting vertices ii and jj with cost A[i][j]A[i][j]. Calculate the cost of the minimum spanning tree of GG.

Input

The first line contains two integers NN and QQ.

Each of the next QQ lines contains five integers X1X_1 X2X_2 Y1Y_1 Y2Y_2 WW, describing one query.

Output

Print the cost of the minimum spanning tree of GG.

Constraints

  • 1≤N,Q≤1051 \le N, Q \le 10^5
  • 1≤X1≤X2<Y1≤Y2≤N1 \le X_1 \le X_2 < Y_1 \le Y_2 \le N
  • ∣W∣≤106|W| \le 10^6
  • Time limit: 8000 ms. Memory limit: 1024 MB.

Examples3

  1. Example 1

    Input
    5 3
    1 1 2 4 10
    2 2 3 4 10
    3 3 4 4 10
    
    Expected output
    0
    
  2. Example 2

    Input
    5 5
    3 3 4 5 -10
    1 2 3 4 20
    4 4 5 5 -10
    2 2 4 4 -20
    1 1 2 4 0
    
    Expected output
    -20
    
  3. Example 3

    Input
    6 8
    1 3 6 6 3
    4 4 6 6 10
    3 3 5 6 -8
    1 2 5 5 -7
    1 2 6 6 -1
    1 3 4 5 6
    3 5 6 6 7
    2 3 6 6 3
    
    Expected output
    -2