HTML & JS
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define openfile ifstream cin; ofstream cout; cin.open("input.txt"); cout.open("output.txt");
#define f(i, x, y) for(int i = x; i < y; i++)
#define all(X) X.begin(), X.end()
#define int long long
#define ll long long
#define key pair<int, int>
#define keyd pair<double, double>
#define ff first
#define ss second
#define double long double
int mod = 1e9+7;
const int inf = 1e18;
using namespace std;

vector<int> g[200001];
int dp[200001][3];

int ans = 0;

void dfs(int s, int p, int lvl)
{
    int sum0 = 0, sum1 = 0, sum2 = 0;
    for(int i : g[s])
    {
        if(i == p) continue;
        dfs(i, s, lvl+1);
        if(lvl < 2) continue;
        sum0 += min(dp[i][0], dp[i][1]); 
        dp[s][1] += min(dp[i][0], min(dp[i][1], dp[i][2]));
        dp[s][2] += min(dp[i][0], dp[i][1]);
    }
    
    if(lvl < 2 || (lvl == 2 && g[s].size() == 1)) return;
    dp[s][0] = inf; dp[s][1]++;
    
    for(int i : g[s])
    {
        if(i == p) continue;
        dp[s][0] = min(dp[s][0], sum0 + max(0ll, dp[i][1] - dp[i][0]));
    }
    
    if(lvl == 2)
        ans += min(dp[s][0], min(dp[s][1], dp[s][2])); 
}

main()
{
    fastread;
    memset(dp, 0, sizeof(dp));
    int n; cin>>n;
    if(n == 1) { cout<<0; return 0; }
    f(i, 1, n)
    {
        int s, d; cin>>s>>d; g[s].pb(d); g[d].pb(s);
    }
    dfs(1, -1, 0);
    
//    f(i, 1, n+1) cout<<dp[i][0]<<" "<<dp[i][1]<<" "<<dp[i][2]<<"\n"; 
    cout<<ans;
}

Generated URL:

Output:

3
Report Bug