# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
94291 | Kastanda | Hard route (IZhO17_road) | C++11 | 12 ms | 12156 KiB |
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>
#define pb push_back
using namespace std;
const int N = 500005;
int n, D[N], C[N];
long long Max, cnt;
vector < int > Adj[N];
void DFS(int v, int p)
{
for (int i = 0; i < Adj[v].size(); i++)
if (Adj[v][i] == p)
swap(Adj[v][i], Adj[v].back()),
Adj[v].pop_back();
if (!Adj[v].size())
{
D[v] = 0;
C[v] = 1;
return ;
}
int Mxd[4] = {-1, -1, -1, -1};
int Cnt[4] = {0, 0, 0, 0};
for (int &u : Adj[v])
{
DFS(u, v);
Mxd[3] = D[u] + 1;
for (int i = 2; i >= 0; i --)
if (Mxd[i + 1] >= Mxd[i])
swap(Mxd[i + 1], Mxd[i]);
}
long long dist = 1LL * Mxd[0] * (Mxd[1] + Mxd[2]);
long long cc = 0;
long long sum = 0;
for (int &u : Adj[v])
{
int d = D[u] + 1;
if (d < Mxd[2])
continue;
if (d == Mxd[0])
{
cc += 1LL * C[u] * Cnt[1] * Cnt[2];
if (Mxd[1] == Mxd[2])
cc -= 1LL * C[u] * sum;
}
if (d == Mxd[1])
{
cc += 1LL * C[u] * Cnt[0] * Cnt[2];
if (Mxd[0] == Mxd[2])
cc -= 1LL * C[u] * sum;
}
if (d == Mxd[2])
{
cc += 1LL * C[u] * Cnt[0] * Cnt[1];
if (Mxd[0] == Mxd[1])
cc -= 1LL * C[u] * sum;
}
if (Mxd[0] == Mxd[1] || Mxd[1] == Mxd[2])
sum += 1LL * C[u] * C[u];
for (int i = 0; i <= 2; i++)
if (d == Mxd[i])
Cnt[i] += C[u];
}
D[v] = Mxd[0];
C[v] = Cnt[0];
if (Mxd[2] == -1)
return ;
if (Max < dist)
Max = dist, cnt = 0;
if (Max == dist)
cnt += cc;
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n - 1; i++)
{
int v, u;
scanf("%d%d", &v, &u);
Adj[v].pb(u);
Adj[u].pb(v);
}
if (n <= 2)
return !printf("0 1");
int root = 0;
for (int i = 1; i <= n; i++)
if (Adj[i].size() > 1)
root = i;
DFS(root, 0);
if (cnt == 0) cnt = 2;
return !printf("%lld %lld\n", Max, cnt >> 1);
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |