This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define ff second
#define ss second
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].ff+1 > dp[at].ff) {
dp[at]=dp[to];
dp[at].ff++;
}
else if(dp[to].ff+1 == dp[at].ff) {
dp[at].ss+=dp[to].ss;
}
}
}
void dfs2(int at, int p) {
sort(g[at].begin(), g[at].end(), [&](int u, int v) {
return dp[u].ff > dp[v].ff;
});
if(g[at].size()>=3) {
ll a = dp[g[at][0]].ff, b = dp[g[at][1]].ff, c = dp[g[at][2]].ff;
ll res = a*(b+c);
ll cntb = 0, cntc = 0, totcnt=0;
for(int to:g[at]) {
if(c == dp[to].ff)totcnt+=cntb*dp[to].ss;
if(b == dp[to].ff)cntb+=dp[to].ss;
}
if(ans.ff == res){
ans.ss+=totcnt;
}
else if(ans.ff < res) {
ans.ff = res;
ans.ss = totcnt;
}
}
pair<ll, ll> fr = {1, 1};
pair<ll, ll> sc = {1, 1};
for(int to:g[at]) {
if(fr.ff < dp[to].ff+1) {
fr=dp[to];
fr.ff++;
}
else if(fr.ff == dp[to].ff+1) {
fr.ss+=dp[to].ss;
}
}
for(int to:g[at]) {
if(dp[to].ff+1==fr.ff)continue;
if(sc.ff < dp[to].ff+1) {
sc=dp[to];
sc.ff++;
}
else if(sc.ff == dp[to].ff+1) {
sc.ss+=dp[to].ss;
}
}
for(int to:g[at]) {
if(to==p)continue;
if(fr.ff == dp[to].ff+1 and fr.ss == dp[to].ss) {
dp[at] = sc;
}
else if(fr.ff == dp[to].ff+1) {
dp[at] = fr;
dp[at].ss -= dp[to].ss;
}
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.ff << " " << ans.ss << "\n";
}
Compilation message (stderr)
road.cpp: In function 'void dfs2(int, int)':
road.cpp:33:18: warning: unused variable 'cntc' [-Wunused-variable]
33 | ll cntb = 0, cntc = 0, totcnt=0;
| ^~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |