結果
問題 | No.806 木を道に |
ユーザー |
![]() |
提出日時 | 2020-11-02 22:09:26 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
WA
|
実行時間 | - |
コード長 | 2,370 bytes |
コンパイル時間 | 749 ms |
コンパイル使用メモリ | 80,788 KB |
実行使用メモリ | 14,720 KB |
最終ジャッジ日時 | 2024-07-22 08:08:03 |
合計ジャッジ時間 | 3,356 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 9 WA * 18 |
ソースコード
#include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T = int> struct Edge { int from, to; T cost; int idx; Edge() = default; Edge(int from, int to, T cost = 1, int idx = -1) : from(from), to(to), cost(cost), idx(idx) {} operator int() const { return to; } }; template<typename T = int> struct Graph { vector<vector<Edge<T>>> g; int es; Graph() = default; explicit Graph(int n) : g(n), es(0) {} size_t size() const { return g.size(); } void add_directed_edge(int from, int to, T cost = 1) { g[from].emplace_back(from, to, cost, es++); } void add_edge(int from, int to, T cost = 1) { g[from].emplace_back(from, to, cost, es); g[to].emplace_back(to, from, cost, es++); } void read(int M, int padding = -1, bool weighted = false, bool directed = false) { for (int i = 0; i < M; i++) { int a, b; cin >> a >> b; a += padding; b += padding; T c = T(1); if (weighted) cin >> c; if (directed) add_directed_edge(a, b, c); else add_edge(a, b, c); } } }; template<typename T = int> struct TreeDiameter : Graph<T> { public: using Graph<T>::Graph; using Graph<T>::g; vector<Edge<T>> path; T build() { to.assign(g.size(), -1); auto p = dfs(0, -1); auto q = dfs(p.second, -1); int now = p.second; while (now != q.second) { for (auto &e : g[now]) { if (to[now] == e.to) { path.emplace_back(e); } } now = to[now]; } return q.first; } explicit TreeDiameter(const Graph<T> &g) : Graph<T>(g) {} private: vector<int> to; pair<T, int> dfs(int idx, int par) { pair<T, int> ret(0, idx); for (auto &e : g[idx]) { if (e.to == par) continue; auto cost = dfs(e.to, idx); cost.first += e.cost; if (ret < cost) { ret = cost; to[idx] = e.to; } } return ret; } }; int main() { int n; cin >> n; TreeDiameter<int> g(n); g.read(n - 1, -1); cout << n - 1 - g.build() << endl; return 0; }