a566中等正權樹直徑的兩次走訪
CPE:Roads in the North (UVa 10308)
由任一點找到直徑端點,再找最遠距離。
解題思路
樹上任兩點只有一條路,因此從任意點出發,用堆疊累加道路長度就能取得到所有點的距離,無須一般圖的Dijkstra。第一趟取最遠點u;正權樹中,這種最遠點必為某條直徑的端點。
第二趟從u出發,最遠距離就是直徑長度。直覺上若u不是端點,把任一最長路徑與起點到u的分岔路比較,就能延伸出不短於原直徑的路。輸入空白行是分組依據,不能把全部token合成一棵樹;EOF時也要處理最後一組,連續空白行不產生額外空圖。
Step-by-step animation
示意:1—2長3,2—3長4,2—4長2
步驟 1 / 3
從1出發
到1、2、3、4的距離為0、3、7、5。
1:0
2:3
3:7
4:5
- 最遠u
- 3
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
using Graph = map<int, vector<pair<int, long long>>>;
pair<long long, int> farthest(const Graph &g, int s) {
pair<long long, int> best{0, s};
vector<tuple<int, int, long long>> st{{s, -1, 0}};
while (!st.empty()) {
auto [u, p, d] = st.back();
st.pop_back();
best = max(best, make_pair(d, u));
for (auto [v, w] : g.at(u))
if (v != p)
st.emplace_back(v, u, d + w);
}
return best;
}
int main() {
Graph g;
string line;
auto finish = [&]() {
if (g.empty())
return;
auto u = farthest(g, g.begin()->first).second;
cout << farthest(g, u).first << '\n';
g.clear();
};
while (getline(cin, line)) {
istringstream in(line);
int a, b;
long long w;
if (!(in >> a >> b >> w)) {
finish();
continue;
}
g[a].emplace_back(b, w);
g[b].emplace_back(a, w);
}
finish();
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。