CSES - Shared codeLink to this code:
https://cses.fi/paste/7b6250d2bd69c63f20d838/
// Code Created BY LEO_VALDEZ
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define sz(x) (int)(x).size()
#define sarr(x) (int)(sizeof(x)/sizeof(x[0]))
#define mp make_pair
#define fast() ios_base::sync_with_stdio(false); cin.tie(NULL);
#define pb push_back
#define p2(x) (1ll<<x)
#define pob pop_back
#define zero (long long)0
#define f first
#define INF 10000000000000
#define s second
const int mod = 1e9 + 7;// make this 98953... if reqd
#define MX (int)2e5+5
vector<int> Adj[MX];
int dp[2][MX];
void DFS(int u, int p)
{
dp[0][u] = 0;
dp[1][u] = -INF;
for(int v: Adj[u])
{
if(v==p)
continue;
DFS(v, u);
dp[0][u] += (max(dp[1][v], dp[0][v]));
int opt = min(dp[0][v]-dp[1][v], zero);
dp[1][u] = max(dp[1][u], opt);
}
dp[1][u]+=dp[0][u];
dp[1][u]++;
return;
}
signed main()
{
int n;
cin >> n;
int m = n-1;
while(m--)
{
int a, b;
cin >> a >> b;
a--;
b--;
Adj[a].pb(b);
Adj[b].pb(a);
}
DFS(0, -1);
int ans = max(dp[0][0], dp[1][0]);
cout << ans << endl;
return 0;
}