Graph Theory Homework
题目
There is a complete graph containing
n
n
n vertices, the weight of the
i
i
i-th vertex is
w
i
w_i
wi.
The length of edge between vertex
i
i
i and
j
j
j
(
i
≠
j
)
(i \ne j)
(i̸=j) is
⌊
∣
w
i
−
w
j
∣
⌋
\lfloor \sqrt{|w_i - w_j|} \rfloor
⌊∣wi−wj∣⌋.
Calculate the length of the shortest path from
1
1
1 to
n
n
n.
Input:
The first line of the input contains an integer
T
T
T
(
1
≤
T
≤
10
)
(1 \le T \le 10)
(1≤T≤10) denoting the number of test cases.
Each test case starts with an integer
n
n
n
(
1
≤
n
≤
1
0
5
)
(1 \le n \le 10 ^ 5)
(1≤n≤105) denoting the number of vertices in the graph.
The second line contains
n
n
n integers, the
i
i
i-th integer denotes
w
i
w_i
wi
(
1
≤
w
i
≤
1
0
5
)
(1 \le w_i \le 10 ^ 5)
(1≤wi≤105).
Output:
For each test case, print an integer denoting the length of the shortest path from 1 1 1 to n n n.
题目大意
给你一个完全图,然后每个节点都有一个权值 w i w_i wi,每两个点之间的距离 d = ⌊ ∣ w i − w j ∣ ⌋ d = \lfloor \sqrt{|w_i - w_j|} \rfloor d=⌊∣wi−wj∣⌋,求从1到n的最短距离是多少
分析
由均值不等式与绝对值三角不等式有:
∣
a
−
b
∣
+
∣
b
−
c
∣
≥
∣
a
−
b
∣
+
∣
b
−
c
∣
≥
∣
a
−
c
∣
\sqrt{|a - b|} + \sqrt{|b - c|} \ge \sqrt{|a - b| + |b - c|} \ge \sqrt{|a - c|}
∣a−b∣+∣b−c∣≥∣a−b∣+∣b−c∣≥∣a−c∣
显然,任意两点之间,直接连接是最短的。
参考代码
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#ifdef LOCAL
#define frein(x) freopen(x, "r", stdin)
#define freout(x) freopen(x, "w", stdout)
#else
#define frein(x)
#define freout(x)
#endif
#define mem(x, v) memset(x, v, sizeof(x))
#define squ(x) ((x) * (x))
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 7;
const int inf = 0x3f3f3f3f;
int arr[maxn];
int main(void){
//frein("data.in");
//freout("data.out");
int T; cin >> T;
while(T--){
int n; cin >> n;
for(int i = 1; i <= n; i++){
cin >> arr[i];
}
int ans = sqrt(abs(arr[1] - arr[n]));
cout << ans << endl;
}
return 0;
}
博客是一道图论作业题,给定一个含n个顶点的完全图,各顶点有权值wi,两点间距离为⌊∣wi−wj∣⌋,要求计算从顶点1到n的最短路径长度。通过均值与绝对值三角不等式分析得出,任意两点直接连接最短。
544

被折叠的 条评论
为什么被折叠?



