题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6343
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Problem Description
There is a complete graph containing n vertices, the weight of the i-th vertex is wi.
The length of edge between vertex i and j (i≠j) is ⌊sqrt(|wi−wj|)⌋.
Calculate the length of the shortest path from 1 to n.
Input
The first line of the input contains an integer T (1≤T≤10) denoting the number of test cases.
Each test case starts with an integer n (1≤n≤10^5) denoting the number of vertices in the graph.
The second line contains n integers, the i-th integer denotes wi (1≤wi≤10^5).
Output
For each test case, print an integer denoting the length of the shortest path from 1 to n.
Sample Input
1
3
1 3 5
Sample Output
2
题意:
给出一张完全图由n个点组成,编号1~n,每个点有一个w[i],对于任意不同两点 i 和 j 之间的边的长度为 $\left\lfloor {\sqrt {\left| {w\left[ i \right] - w\left[ j \right]} \right|} } \right\rfloor$,
要求给出从1到n的最短路长度。
题解:
对于任意两点 i 和 j,edge(i,j)这条边是最短路;
证:
对于任意两点 i 和 j,假设另外任取一点 k,我们先证明 $\sqrt {\left| {w_i - w_j } \right|} \le \sqrt {\left| {w_i - w_k } \right|} + \sqrt {\left| {w_k - w_j } \right|}$,
首先根据 ${\left( {\sqrt a + \sqrt b } \right)^2 = a + b + 2\sqrt {ab} \ge a + b}$ 可知 $\sqrt {a + b} \le \sqrt a + \sqrt b$ ,其中 $a,b \ge 0$,
就有:
$\sqrt {\left| {w_i - w_k } \right|} + \sqrt {\left| {w_k - w_j } \right|} \ge \sqrt {\left| {w_i - w_k } \right| + \left| {w_k - w_j } \right|}$
取等条件是 ${\left| {w_i - w_k } \right|\left| {w_k - w_j } \right| = 0}$,
又根据绝对值不等式可知:
$\left| {w_i - w_k } \right| + \left| {w_k - w_j } \right| \ge \left| {w_i - w_k + w_k - w_j } \right| = \left| {w_i - w_j } \right|$
取等条件是 ${\left| {w_i - w_k } \right|\left| {w_k - w_j } \right| \ge 0}$,
相应的就有:
$\sqrt {\left| {w_i - w_k } \right| + \left| {w_k - w_j } \right|} \ge \sqrt {\left| {w_i - w_j } \right|}$
即证明了:
$\sqrt {\left| {w_i - w_j } \right|} \le \sqrt {\left| {w_i - w_k } \right|} + \sqrt {\left| {w_k - w_j } \right|}$
取等条件为 ${\left| {w_i - w_k } \right|\left| {w_k - w_j } \right| = 0}$。