Hackerrank Going to the Office

传送门

Problem Statement

Ms.Kox enjoys her job, but she does not like to waste extra time traveling to and from her office. After working for many years, she knows the shortest-distance route to her office on a regular day.

Recently, the city began regular maintenance of various roads. Every day a road gets blocked and no one can use it that day, but all other roads can be used. You are Ms. Kox's new intern and she needs some help. Every day, you need to determine the minimum distance that she has to travel to reach her office.

Input Format
There are N cities numbered 0 to N-1 and M bidirectional roads.

  • The first line of the input contains two integers N and M.
  • M lines follow, each containing three space-separated integers u , v and w, where u and v are cities connected by a bi-directional road and w is the length of this road. There is at most one road between any two cities and no road connects a city to itself.
  • The next line contains two integers S and D. S is the city where Ms. Kox lives and D is the city where her office is located.
  • The next line contains an integer Q, the number of queries.
  • Q lines follow, each containing two integers u and v, where the road between u and v has been blocked that day.

Output Format
Output Q lines, with each line containing the minimum distance Ms.Kox has to travel on that day. If there is no path, print "Infinity".

Constraints
0 < N < 200,000
0 < M < 200,000
0 < Q < 200,000
0 <= S , D < N

Sample Input

6 9  
0 1 1  
1 2 1  
2 3 1  
3 4 1  
4 5 1  
2 4 5  
3 5 8  
1 3 3  
0 2 4  
0 5  
9  
0 1  
1 2  
2 3  
3 4  
4 5  
2 4  
3 5  
1 3  
0 2

Sample Output

7  
6  
6  
8  
11  
5  
5  
5


Solution
不失一般性,先假设无向图G连通。
考虑G的以s为根的最短路树(SPT)。
删除边(u, v)后原SPT分裂成两部分,子树S和子树V。
若边(u, v)不在原SPT的s-t路上,易见最短路长度不变。
否则,若(u, v)不是G的s-t割,则
新最短路存在且可取成如下形式:
从s出发沿子树s走到点x, 经一条连接子树S与子树V的不在原SPT中的 (S-V non-STP) 边 (x, y)走到子树V中,只经过子树V中的点从y走到t。


Proof

首先,显而易见删除边(u,v)后,图G中的任意s-t路都包含至少一条S-V non-STP边。
接下来证明:存在一条新s-t最短路,只经过一条S-V non-STP边。
反证法:假设所有新s-t最短路都经过至少两条S-V non-STP边,
任取一条新s-t最短路P0,设P0最晚经过的S-V non-STP边为(x, y),则有
|P0 (s, x)| >= |PS (s, x)|
PS (s, x)代替P0 (s, x)即导出矛盾。

将上述讨论形式化:
一定存在一条形如
P(s, t) = P0 (s, x) + (x, y) +  PV (y, t)
新s-t最短路

下一步证明:存在一条只经过子树V中点的y-t最短路PV (y, t)满足:
|PV(y, t)| = |PG(y, t)|
PG(y, t)表示在原图G中的某条y-t最短路

仍采用反证法:
假设原图G中的所有y-t最短路都要经过子树S中的点,





 










  

posted @ 2016-11-22 11:43  Pat  阅读(573)  评论(0编辑  收藏  举报