2

The problem gives a MST $T$ and a series of $Q$ queries, each one with a new edge $e = \{u,v\}$ such that no edge between $u$ and $v$ exists in $T$. For every query, we have to improve $T$ with $e$ and print the new weight of $T$.

The best I can do is run a DFS ($O(|V|)$) to find the current path $P$ between $u$ and $v$, and find the heaviest edge $e_\text{max}$ in $P$. If $w(e) > w(e_\text{max})$, we improve $T$ removing $e_\text{max}$ and inserting $e$. The overall running time for a test case is $O(Q|V|)$.

Does anybody know an asymptotically faster algorithm for this problem?

matheuscscp
  • 325
  • 1
  • 4
  • 11
  • 2
  • "Faster than $O(_)$" is an empty statement. You want to use $\Theta$. 2) What makes you think there is one? Is the one you have too slow in practice? 3) How large is $Q$? Individual queries can certainly be sped up by preprocessing (e.g., create a PQ for all node pairs and put all edges between the two in) but that will comes as a cost. 4) Note that DFS actually takes time in $\Theta(|V|)$ for you, since any given MST has $|V| - 1$ edges.
  • – Raphael Aug 26 '15 at 07:28
  • I think there might be a better approach, depending on how you constructed the MST. If it was constructed with Kruskal's and the total order of the edges' weights was cached, then I think there should be an asymptotically faster approach then having to run a DFS on the graph, I'm just not exactly sure right now what the procedure would entail to guarantee an MST. – Francesco Gramano Aug 26 '15 at 15:42
  • @Raphael 1) Whatever. 2) Because my current solution exceeds the time limit of the online judge and certainly is not a constant factor that will save me. 3) $Q$ is large. 4) Of course I know that. 5) Do you know what competitive programming means? Training for that should really improve your algorithm skills. A red programmer on codeforces answered this question almost as if it was an easy one. But thanks for trying to help! – matheuscscp Aug 26 '15 at 15:54
  • And DFS takes time $O(|V|)$. In the best case we traverse only 2 edges, instead of $\Theta(|V|)$. – matheuscscp Aug 26 '15 at 16:01
  • 1
    @matheuscscp ad 1 + second comment: Oh, you got some lip despite not knowing how to read Landau notation. You should read this. ad 2+5: you nowhere state that you are interested in runtime in seconds, nor on what imputs, nor what the required interface is, nor what your implementation looks like. FWIW, while programming is offtopic here there may still be algorithmic improvements, but it's impossible you tell from your question what you may be doing wrong. – Raphael Aug 26 '15 at 19:24
  • Okay, my DFS is $\Theta(1)$ in the best case, and $\Theta(|V|)$ in the freaking worst case. If you don't get that by the harmless abuses $\Omega(1)$ and $O(|V|)$... But thanks again for trying to help! – matheuscscp Aug 26 '15 at 19:47