Dynamic MST

View as PDF

Submit solution

Points: 40 (partial)
Time limit: 1.8s
Memory limit: 128M

Problem type
Allowed languages
Ada, Assembly, Awk, Brain****, C, C#, C++, COBOL, CommonLisp, D, Dart, F#, Forth, Fortran, Go, Groovy, Haskell, Intercal, Java, JS, Kotlin, Lisp, Lua, Nim, ObjC, OCaml, Octave, Pascal, Perl, PHP, Pike, Prolog, Python, Racket, Ruby, Rust, Scala, Scheme, Sed, Swift, TCL, Text, Turing, VB, Zig

Given N vertices and M weighted bidirectional edges, Bruce knows how to find the Minimal Spanning Tree (MST). But if the weight of each edge is changing, Bruce doesn't know how to efficiently find the MST after each change. Can you write a program to help Bruce?

Input Specification

The first line of input will consist of three integers, N, M and Q, which are the number of vertices, number of edges, and number of weight changes.

Each of the next M lines will consist of three integers, x, y and z (1\leq x, y \leq N, 0 \leq z \leq 50\,000\,000), which represents the bidirectional edge between x and y has the cost z.

Each of the next Q lines will consist of two integers, k and d (1\leq k \leq M, 0 \leq d \leq 50\,000\,000), which represents the k-th edge's cost changes to d.

Output Specification

Output Q lines. The line k consists of 1 integer, the cost of MST after the first k changes.


20% cases N\leq 1\,000, M \leq 6\,000, Q\leq 6\,000

40% cases N\leq 1\,000, M \leq 50\,000, Q\leq 8\,000

100% cases N\leq 20\,000, M \leq 50\,000, Q\leq 50\,000

Sample Input

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

Sample Output



  • 11
    koosaga  commented on Jan. 1, 2018, 9:46 a.m.

    What if graph doesn't have minimum spanning tree?

    • 6
      Kirito  commented on Feb. 26, 2019, 10:36 a.m.

      For anyone solving this problem in the future, it is guaranteed that the graph is connected.

  • 10
    imaxblue  commented on March 14, 2017, 11:09 p.m.

    block size 400 is more effective than either block size 500, 200, 250, 125 or 100

    • 3
      wleung_bvg  commented on Aug. 24, 2017, 4:09 a.m.

      It does seem to vary based on the implementation

      • 3
        bruce  commented on Aug. 24, 2017, 8:40 a.m.

        Time complexity is supposed to be O(QlogNlogN) and time limit is supposed to be 2 sec.