Submission #1002577

#TimeUsernameProblemLanguageResultExecution timeMemory
1002577BF001Hard route (IZhO17_road)C++17
100 / 100
368 ms105044 KiB
#include <bits/stdc++.h> using namespace std; #define int long long #define N 500005 #define fi first #define se second typedef pair<int, int> ii; int ma[N], cnt[N], n, res, way = 1; vector<int> adj[N]; void dfs(int u, int p){ cnt[u] = 1; for (auto x : adj[u]){ if (x == p) continue; dfs(x, u); if (ma[x] + 1 == ma[u]){ cnt[u] += cnt[x]; } else if (ma[x] + 1 > ma[u]){ ma[u] = ma[x] + 1; cnt[u] = cnt[x]; } } } bool cmp(int& a, int& b){ return ma[a] > ma[b]; } void rr(int u, int p){ sort(adj[u].begin(), adj[u].end(), cmp); if (adj[u].size() >= 3){ int a = ma[adj[u][0]] + 1, b = ma[adj[u][1]] + 1, c = ma[adj[u][2]] + 1; int m = a * (b + c); int w = 0; int db = 0; a--, b--, c--; for (auto x : adj[u]){ if (ma[x] == c) w += cnt[x] * db; if (ma[x] == b) db += cnt[x]; } if (m > res) res = m, way = w; else if (m == res) way += w; } ii fir = {0, 1}, sed = {0, 1}; int tma = ma[u], tmw = cnt[u]; for (auto x : adj[u]){ if (ma[x] + 1> fir.fi){ sed = fir; fir = {ma[x] + 1, cnt[x]}; } else if (ma[x] + 1 == fir.fi) fir.se += cnt[x]; else if (ma[x] + 1 > sed.fi){ sed = {ma[x] + 1, cnt[x]}; } else if (ma[x] + 1 == sed.fi) sed.se += cnt[x]; } for (auto x : adj[u]){ if (x == p) continue; ma[u] = fir.fi, cnt[u] = fir.se; if (fir.fi == ma[x] + 1 && fir.se == cnt[x]) ma[u] = sed.fi , cnt[u] = sed.se; else if (fir.fi == ma[x] + 1) cnt[u] -= cnt[x]; rr(x, u); } ma[u] = tma, cnt[u] = tmw; } signed main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> n; for (int i = 1; i <= n - 1; i++){ int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } dfs(1, 0); rr(1, 0); cout << res << " " << way; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...