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 <iostream>
#include <vector>
#define X first
#define Y second
#define MP make_pair
#define ll long long
using namespace std;
const int N = 5e5 + 12;
const int INF = 2e9;
int n, m;
ll ans, mx_ans;
pair<int, int> dp[N];
vector< int > g[N];
void dfs(int v, int pr){
for(int to: g[v]){
if(to != pr){
dfs(to, v);
if(dp[v].X < dp[to].X + 1){
dp[v] = dp[to], dp[v].X++;
}
else if(dp[v].X == dp[to].X + 1){
dp[v].Y += dp[to].Y;
}
}
}
if(g[v].size() == 1 && pr != -1)
dp[v] = MP(0, 1);
}
void rdfs(int v, int pr, pair<int, int> mx){
pair<int, int> mx1 = mx, mx2 = MP(0, 0), mx3 = MP(0, 0);
int f1 = pr, f2 = 0, f3 = 0;
for(int to: g[v]){
if(to != pr){
pair<int, int> tmp = MP(dp[to].X + 1, dp[to].Y);
if(mx1 < tmp)
mx3 = mx2, mx2 = mx1, mx1 = tmp, f3 = f2, f2 = f1, f1 = to;
else if(mx2 < tmp)
mx3 = mx2, mx2 = tmp, f3 = f2, f2 = to;
else if(mx3 < tmp)
mx3 = tmp, f3 = to;
}
}
if(mx3.X > 0){
ll tmp = mx1.X * 1ll * (mx2.X + mx3.X);
if(tmp > mx_ans){
mx_ans = tmp;
if(mx1.X == mx2.X && mx2.X == mx3.X)
ans = 3 * mx1.Y * 1ll * mx2.Y * mx3.Y;
else if(mx1.X == mx2.X)
ans = (mx1.Y + mx2.Y) * 1ll * mx3.Y;
else if(mx1.X == mx3.X)
ans = (mx1.Y + mx3.Y) * 1ll * mx2.Y;
else
ans = mx2.Y * 1ll * mx3.Y;
}
else if(tmp == mx_ans){
if(mx1.X == mx2.X && mx2.X == mx3.X)
ans += 3 * mx1.Y * 1ll * mx2.Y * mx3.Y;
else if(mx1.X == mx2.X)
ans += (mx1.Y + mx2.Y) * 1ll * mx3.Y;
else if(mx1.X == mx3.X)
ans += (mx1.Y + mx3.Y) * 1ll * mx2.Y;
else
ans += mx2.Y * 1ll * mx3.Y;
}
}
if(pr == -1 && g[v].size() == 1){
mx2 = MP(0, 1);
} mx1.X += 1, mx2.X += 1, mx3.X += 1;
for(int to: g[v]){
if(to != pr){
if(to != f1){
rdfs(to, v, mx1);
}
else if(to != f2){
rdfs(to, v, mx2);
}
else{
rdfs(to, v, mx3);
}
}
}
}
int main () {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 1, x, y;i < n;i++){
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1, -1);
rdfs(1, -1, MP(0, 0));
if(!mx_ans)
ans = 1;
cout << mx_ans << " " << ans;
}
Compilation message (stderr)
road.cpp: In function 'void rdfs(int, int, std::pair<int, int>)':
road.cpp:36:23: warning: variable 'f3' set but not used [-Wunused-but-set-variable]
36 | int f1 = pr, f2 = 0, f3 = 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... |