#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 1e9;
const int N = 100002;
ll n;
vector<int> graph[N];
ll x[N];
ll papa[N];
ll dp[N][2];
void dfs(int v, int p)
{
papa[v] = p;
for (auto u : graph[v]) if (u != p)
{
dfs(u, v);
}
}
int answer()
{
return min(dp[0][0], dp[0][1]);
}
void initialize(int n0, vector<int> a, vector<int> b)
{
n = n0;
for (int i = 0; i < n - 1; i++)
{
a[i]--, b[i]--;
graph[a[i]].push_back(b[i]);
graph[b[i]].push_back(a[i]);
}
for (int i = 0; i < n; i++)
{
x[i] = -1;
}
dfs(0, 0);
}
int cat(int v)
{
v--;
x[v] = 0;
pair<int, int> pdp = {dp[v][0], dp[v][1]};
dp[v][1] = INF;
while (papa[v] != v)
{
pair<int, int> sdp = {dp[papa[v]][0], dp[papa[v]][1]};
dp[papa[v]][0] -= min(pdp.first, pdp.second + 1);
dp[papa[v]][1] -= min(pdp.first + 1, pdp.second);
dp[papa[v]][0] += min(dp[v][0], dp[v][1] + 1);
dp[papa[v]][1] += min(dp[v][0] + 1, dp[v][1]);
pdp = sdp;
v = papa[v];
}
return answer();
}
int dog(int v)
{
v--;
x[v] = 1;
pair<int, int> pdp = {dp[v][0], dp[v][1]};
dp[v][0] = INF;
while (papa[v] != v)
{
pair<int, int> sdp = {dp[papa[v]][0], dp[papa[v]][1]};
dp[papa[v]][0] -= min(pdp.first, pdp.second + 1);
dp[papa[v]][1] -= min(pdp.first + 1, pdp.second);
dp[papa[v]][0] += min(dp[v][0], dp[v][1] + 1);
dp[papa[v]][1] += min(dp[v][0] + 1, dp[v][1]);
pdp = sdp;
v = papa[v];
}
return answer();
}
int neighbor(int v)
{
v--;
x[v] = -1;
pair<int, int> pdp = {dp[v][0], dp[v][1]};
dp[v][0] = 0, dp[v][1] = 0;
for (auto u : graph[v]) if (u != papa[v])
{
dp[v][0] += min(dp[u][0], dp[u][1] + 1);
dp[v][0] += min(dp[u][0] + 1, dp[u][1]);
}
while (papa[v] != v)
{
pair<int, int> sdp = {dp[papa[v]][0], dp[papa[v]][1]};
dp[papa[v]][0] -= min(pdp.first, pdp.second + 1);
dp[papa[v]][1] -= min(pdp.first + 1, pdp.second);
dp[papa[v]][0] += min(dp[v][0], dp[v][1] + 1);
dp[papa[v]][1] += min(dp[v][0] + 1, dp[v][1]);
pdp = sdp;
v = papa[v];
}
return answer();
}
#ifdef LOCAL
int main()
{
int n;
cin >> n;
vector<int> a(n - 1), b(n - 1);
for (int i = 0; i < n - 1; i++)
{
cin >> a[i] >> b[i];
}
initialize(n, a, b);
int q;
cin >> q;
while (q--)
{
int t, v;
cin >> t >> v;
if (t == 1) cout << cat(v) << endl;
if (t == 2) cout << dog(v) << endl;
if (t == 3) cout << neighbor(v) << endl;
}
}
#endif // LOCAL
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
2 ms |
2688 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
2 ms |
2688 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
2 ms |
2688 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |