# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1234252 | Jer | Duathlon (APIO18_duathlon) | C++20 | 1096 ms | 21692 KiB |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 100005;
const int LOG = 20;
vector<int> con[MAXN];
vector<int> parent(MAXN);
vector<int> depth(MAXN);
vector<vector<int>> up(LOG, vector<int>(MAXN));
vector<int> component_nodes;
vector<bool> visited(MAXN);
int n, m;
void dfs(int u, int par)
{
parent[u] = par;
depth[u] = depth[par] + 1;
visited[u] = true;
component_nodes.push_back(u);
for (int v : con[u])
if (v != par && !visited[v])
dfs(v, u);
}
void build_up_table()
{
for (int u : component_nodes)
up[0][u] = parent[u];
for (int k = 1; k < LOG; ++k)
for (int u : component_nodes)
up[k][u] = up[k - 1][up[k - 1][u]];
}
int lca(int u, int v)
{
if (depth[u] < depth[v])
swap(u, v);
for (int k = LOG - 1; k >= 0; --k)
if (depth[u] - (1 << k) >= depth[v])
u = up[k][u];
if (u == v)
return u;
for (int k = LOG - 1; k >= 0; --k)
if (up[k][u] != up[k][v])
u = up[k][u], v = up[k][v];
return parent[u];
}
int compute_distance(int u, int v)
{
int anc = lca(u, v);
return depth[u] + depth[v] - 2 * depth[anc];
}
int main()
{
scanf("%d%d", &n, &m);
int a, b;
for (int i = 0; i < m; ++i)
{
scanf("%d%d", &a, &b);
con[a].push_back(b);
con[b].push_back(a);
}
ll total = 0;
for (int i = 1; i <= n; ++i)
if (!visited[i])
{
component_nodes.clear();
depth[0] = -1; // so that root depth = 0
dfs(i, 0);
build_up_table();
for (int x : component_nodes)
for (int y : component_nodes)
if (x < y)
{
int d = compute_distance(x, y);
if (d >= 2)
total += d - 1;
}
}
printf("%lld\n", total * 2LL);
return 0;
}
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... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |