一、Problem
很久以前,T王國空前繁榮。爲了更好地管理國家,王國修建了大量的快速路,用於連接首都和王國內的各大城市。
爲節省經費,T國的大臣們經過思考,制定了一套優秀的修建方案,使得任何一個大城市都能從首都直接或者通過其他大城市間接到達。同時,如果不重複經過大城市,從首都到達每個大城市的方案都是唯一的。
J是T國重要大臣,他巡查於各大城市之間,體察民情。所以,從一個城市馬不停蹄地到另一個城市成了J最常做的事情。他有一個錢袋,用於存放往來城市間的路費。
聰明的J發現,如果不在某個城市停下來修整,在連續行進過程中,他所花的路費與他已走過的距離有關,在走第x千米到第x+1千米這一千米中(x是整數),他花費的路費是x+10這麼多。也就是說走1千米花費11,走2千米要花費23。
J大臣想知道:他從某一個城市出發,中間不休息,到達另一個城市,所有可能花費的路費中最多是多少呢?
輸入格式:
輸入的第一行包含一個整數n,表示包括首都在內的T王國的城市數。
城市從1開始依次編號,1號城市爲首都。
接下來n-1行,描述T國的高速路(T國的高速路一定是n-1條)
每行三個整數Pi, Qi, Di,表示城市Pi和城市Qi之間有一條高速路,長度爲Di千米。
輸出格式:
輸出一個整數,表示大臣J最多花費的路費是多少。
樣例輸入:
5
1 2 2
1 3 1
2 4 5
2 5 4
樣例輸出:
135
樣例說明:
大臣J從城市4到城市5要花費135的路費。
二、Solution
方法一:2 * dfs 求樹的直徑
- 本題可理解爲在一棵無向無環圖上求任意兩點之間的最長度。
- 求法較簡單:
- 第一遍 dfs 求出距離根節點 1 最遠的點 m。
- 第二遍 dfs 從 m 開始再求一遍距離 m 最遠距離。
- 最後用這個公式…愉快地算出…
公式推導:
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
int N, tot, m, max;
Edge[] e;
int[] head;
boolean[] vis;
void add(int u, int v, int w) {
e[++tot] = new Edge();
e[tot].to = v;
e[tot].w = w;
e[tot].next = head[u];
head[u] = tot;
}
void dfs(int x, int d) {
if (d > max) {
max = d;
m = x;
}
for (int i = head[x]; i != 0; i = e[i].next) {
int to = e[i].to, w = e[i].w;
if (!vis[to]) {
vis[to] = true;
dfs(to, d+w);
vis[to] = false;
}
}
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
N = sc.nextInt();
e = new Edge[2*N+5];
head = new int[N+5];
for (int i = 0; i < N-1; i++) {
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
add(a, b, c);
add(b, a, c);
}
vis = new boolean[N+5];
vis[1] = true;
dfs(1, 0);
vis = new boolean[N+5];
vis[m] = true;
dfs(m, 0);
System.out.println(10*max + (max+1)*max / 2);
}
class Edge {
int to, w, next;
Edge() {}
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
方法二:Floyd 求最短距離的最大者
1/2…
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
long[][] dp;
int N, INF = 0x3f3f3f3f; long max;
void floyd() {
for (int k = 1; k <= N; k++)
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++) {
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j]);
if (dp[i][j] != INF)
max = Math.max(max, dp[i][j]);
}
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
N = sc.nextInt();
dp = new long[N+5][N+5];
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++) {
if (i != j) dp[i][j] = INF;
else dp[i][j] = 0;
}
for (int i = 1; i < N; i++) {
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
dp[a][b] = dp[b][a] = c;
}
floyd();
long cash = 0;
for (long i = 1; i <= max; i++) {
cash += 10 + i;
}
System.out.println(cash);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}