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>
// https://oj.uz/problem/view/CEOI17_mousetrap
using namespace std;
void dfs(int node, int parent, vector<vector<int>>& graph, vector<int>& parents, vector<vector<int>>& depths, int depth = 0) {
if (depths.size() <= depth) {
depths.resize(4 * (depth + 1));
}
depths[depth].push_back(node);
for (int child : graph[node]) {
if (child == parent) continue;
parents[child] = node;
dfs(child, node, graph, parents, depths, depth + 1);
}
}
auto max2(const vector<int>& adjacent, const vector<int>& dp, int parent) {
if (adjacent.size() < 2)
return 0;
auto it = adjacent.cbegin();
auto sentinel = adjacent.cend();
if (dp[*it] == parent) {
it++;
}
auto max1 = dp[*it++];
if (it == sentinel || dp[*it] == parent) {
it++;
}
if (!(it < sentinel)) {
return 0;
}
auto max2 = dp[*it++];
if (max1 < max2) {
swap(max1, max2);
}
for (; it < sentinel; it++) {
if (dp[*it] == parent) {
continue;
}
if (dp[*it] > max1) {
max2 = max1;
max1 = dp[*it];
} else if (dp[*it] > max2) {
max2 = dp[*it];
}
}
return max2;
}
int main() {
int n, t, m;
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> t >> m;
vector<vector<int>> graph(n+1);
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
assert(find(graph[t].begin(), graph[t].end(), m) != graph[t].end());
graph[t] = {m};
vector<int> parents(n+1);
vector<vector<int>> depths;
parents[t] = 0;
dfs(t, 0, graph, parents, depths);
vector<int> dp(n+1);
for (int depth = depths.size() - 1; depth >= 0; depth--) {
auto& row = depths[depth];
for (int node : row) {
dp[node] = graph[node].size() + max2(graph[node], dp, parents[node]);
}
}
cout << dp[m] << '\n';
}
Compilation message (stderr)
mousetrap.cpp: In function 'void dfs(int, int, std::vector<std::vector<int> >&, std::vector<int>&, std::vector<std::vector<int> >&, int)':
mousetrap.cpp:8:23: warning: comparison of integer expressions of different signedness: 'std::vector<std::vector<int> >::size_type' {aka 'long unsigned int'} and 'int' [-Wsign-compare]
8 | if (depths.size() <= depth) {
| ~~~~~~~~~~~~~~^~~~~~~~
# | 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... |