QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#294290 | #7936. Eliminate Tree | fxhd | TL | 0ms | 3860kb | C++17 | 2.4kb | 2023-12-30 11:19:53 | 2023-12-30 11:19:54 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#include "debug.hpp"
#else
#define dbg(...) 0
#endif
int solve(const vector<vector<int>>& adj) {
int n = adj.size();
int inf = 3 * n;
vector<int> parent(n, -1), order; order.reserve(n);
{
auto dfs = [&](auto&& self, int u, int pa) -> void {
for (int v : adj[u]) if (v != pa) {
parent [v] = u;
self(self, v, u);
}
order.push_back(u);
};
dfs(dfs, 0, -1);
}
vector<vector<int>> children(n);
for (int i = 0; i < n; ++i) if (parent[i] >= 0) {
children[parent[i]].push_back(i);
}
vector<pair<int, int>> dp(n);
for (int u : order) {
const vector<int>& ch = children[u];
int nch = ch.size();
if (nch == 0) {
dp[u] = {2, 0};
continue;
}
int sum0 = 0;
int min1 = numeric_limits<int>::max();
for (int v : ch) {
sum0 += dp[v].first;
min1 = min(min1, dp[v].second - dp[v].first);
}
dp[u] = {min(2 + sum0, 1 + sum0 + min1), sum0};
}
int ans = dp[0].first;
vector<pair<int, int>> dp2(n);
dp2[0] = {0, 0};
reverse(order.begin(), order.end());
for (int u : order) {
const vector<int>& ch = children[u];
int nch = ch.size();
vector<int> prefix_min(n + 1, inf), suffix_min(n + 1, inf);
int sum0 = dp2[u].first;
for (int i = 0; i < nch; ++i) {
prefix_min[i + 1] = min(prefix_min[i], dp[ch[i]].second - dp[ch[i]].first);
sum0 += dp[ch[i]].first;
}
for (int i = nch - 1; i >= 0; --i) {
suffix_min[i] = min(suffix_min[i + 1], dp[ch[i]].second - dp[ch[i]].first);
}
for (int i = 0; i < nch; ++i) {
int v = ch[i];
dp2[v] = {min(2 + sum0 - dp[v].first, 1 + sum0 - dp[v].first + min(prefix_min[i], suffix_min[i + 1])), sum0 - dp[v].first};
}
}
for (int u = 1; u < n; ++u) {
int sum0 = dp2[u].first;
int min1 = dp2[u].second - dp2[u].first;
for (int v : children[u]) {
sum0 += dp[v].first;
min1 = min(min1, dp[v].second - dp[v].first);
}
ans = min(ans, min(2 + sum0, 1 + sum0 + min1));
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<vector<int>> adj(n);
for (int i = 1; i < n; ++i) {
int u, v;
cin >> u >> v;
--u; --v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cout << solve(adj) << '\n';
}
詳細信息
Test #1:
score: 100
Accepted
time: 0ms
memory: 3624kb
input:
5 1 2 2 3 3 4 3 5
output:
4
result:
ok 1 number(s): "4"
Test #2:
score: 0
Accepted
time: 0ms
memory: 3860kb
input:
4 1 2 2 3 3 4
output:
2
result:
ok 1 number(s): "2"
Test #3:
score: -100
Time Limit Exceeded
input:
196666 32025 108673 181779 17115 162570 134230 93003 39673 89144 1269 185919 154408 34896 65369 35860 44720 55698 1390 45520 189805 147867 124511 135459 132555 87303 18031 176314 59695 33352 130640 87272 39716 35749 108807 143493 94486 126512 116598 40212 70895 132216 80855 22241 188737 150354 17346...