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 <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <random>
#include <complex>
#include <iomanip>
#include <cassert>
#include <functional>
using namespace std;
typedef long long ll;
const int N = 1e5 + 7;
vector <int> g[N];
void initialize(int n, vector <int> a, vector <int> b) {
for (int i = 0; i + 1 < n; ++i) {
--a[i], --b[i];
g[a[i]].push_back(b[i]);
g[b[i]].push_back(a[i]);
}
}
bool have_cat[N], have_dog[N];
int dp[N][3];
const int Inf = 1e9;
void dfs(int u, int p) {
dp[u][0] = dp[u][1] = dp[u][2] = 0;
for (auto v : g[u]) {
if (v != p) {
dfs(v, u);
dp[u][0] += min(min(dp[v][0], dp[v][2]), dp[v][1] + 1);
dp[u][1] += min(min(dp[v][1], dp[v][2]), dp[v][0] + 1);
dp[u][2] += min(dp[v][2], min(dp[v][0] + 1, dp[v][1] + 1));
}
}
if (have_cat[u]) {
dp[u][1] = Inf;
dp[u][2] = Inf;
}
if (have_dog[u]) {
dp[u][0] = Inf;
dp[u][2] = Inf;
}
}
int cat(int v) {
--v;
have_cat[v] = true;
dfs(0, -1);
int ans = Inf;
for (int i = 0; i < 3; ++i) ans = min(ans, dp[0][i]);
return ans;
}
int dog(int v) {
--v;
have_dog[v] = true;
dfs(0, -1);
int ans = Inf;
for (int i = 0; i < 3; ++i) ans = min(ans, dp[0][i]);
return ans;
}
int neighbor(int v) {
--v;
have_cat[v] = have_dog[v] = false;
dfs(0, -1);
int ans = Inf;
for (int i = 0; i < 3; ++i) ans = min(ans, dp[0][i]);
return ans;
}
#ifdef LOCAL
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
int n;
cin >> n;
vector <int> a(n - 1), b(n - 1);
for (int i = 0; i + 1 < n; ++i) {
cin >> a[i] >> b[i];
}
initialize(n, a, b);
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int t, v;
cin >> t >> v;
if (t == 1) {
cout << cat(v) << '\n';
} else if (t == 2) {
cout << dog(v) << '\n';
} else {
cout << neighbor(v) << '\n';
}
}
}
#endif
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |