Submission #997633

#TimeUsernameProblemLanguageResultExecution timeMemory
997633fuad27Hard route (IZhO17_road)C++17
100 / 100
324 ms82144 KiB
#include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 500100; vector<int> g[N]; int n; pair<int,int> dp[N]; pair<ll,ll> ans={0, 1}; void dfs1(int at, int p) { dp[at] = {1, 1}; for(int to:g[at]) { if(to==p)continue; dfs1(to, at); if(dp[to].first+1 > dp[at].first) { dp[at]=dp[to]; dp[at].first++; } else if(dp[to].first+1 == dp[at].first) { dp[at].second+=dp[to].second; } } } void dfs2(int at, int p) { sort(g[at].begin(), g[at].end(), [&](int u, int v) { return dp[u].first > dp[v].first; }); if(g[at].size()>=3) { ll a = dp[g[at][0]].first, b = dp[g[at][1]].first, c = dp[g[at][2]].first; ll res = a*(b+c); ll cntb = 0, cntc = 0, totcnt=0; for(int to:g[at]) { if(c == dp[to].first)totcnt+=cntb*dp[to].second; if(b == dp[to].first)cntb+=dp[to].second; } if(ans.first == res){ ans.second+=totcnt; } else if(ans.first < res) { ans.first = res; ans.second = totcnt; } } pair<ll, ll> fr = {1, 1}; pair<ll, ll> sc = {1, 1}; for(int to:g[at]) { if(fr.first < dp[to].first+1) { fr=dp[to]; fr.first++; } else if(fr.first == dp[to].first+1) { fr.second+=dp[to].second; } } for(int to:g[at]) { if(dp[to].first+1==fr.first)continue; if(sc.first < dp[to].first+1) { sc=dp[to]; sc.first++; } else if(sc.first == dp[to].first+1) { sc.second+=dp[to].second; } } for(int to:g[at]) { if(to==p)continue; if(fr.first == dp[to].first+1 and fr.second == dp[to].second) { dp[at] = sc; } else if(fr.first == dp[to].first+1) { dp[at] = fr; dp[at].second -= dp[to].second; } else { dp[at] = fr; } dfs2(to, at); } } signed main () { cin.tie(0)->sync_with_stdio(0); cin >> n; for(int i = 1;i<n;i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } dfs1(1, 0); dfs2(1, 0); cout << ans.first << " " << ans.second << "\n"; }

Compilation message (stderr)

road.cpp: In function 'void dfs2(int, int)':
road.cpp:31:18: warning: unused variable 'cntc' [-Wunused-variable]
   31 |     ll cntb = 0, cntc = 0, totcnt=0;
      |                  ^~~~
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...