結果

問題 No.2677 Minmax Independent Set
ユーザー maeshun
提出日時 2024-03-16 12:29:43
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 318 ms / 2,000 ms
コード長 2,069 bytes
コンパイル時間 3,963 ms
コンパイル使用メモリ 255,472 KB
最終ジャッジ日時 2025-02-20 06:47:35
ジャッジサーバーID
(参考情報)
judge1 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 61
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#include <atcoder/all>
using namespace atcoder;
#define rep(i, n) for(int i=0;i<(n);++i)
#define rep1(i, n) for(int i=1;i<=(n);i++)
#define ll long long
using mint = modint;
using P = pair<ll,ll>;
using lb = long double;
#ifdef LOCAL
#  include <debug_print.hpp>
#  define dbg(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__)
#else
#  define dbg(...) (static_cast<void>(0))
#endif

// Rerooting
// https://youtu.be/zG1L4vYuGrg?t=7092
// TODO: vertex info, edge info
struct Rerooting {
  struct DP {
    int b, w;
    DP(int b = 0 , int w = 0) :b(b),w(w) {}
    DP operator+(const DP& a) const {
        return {b + max(a.b, a.w), w+a.w};        
    }
    DP addRoot() const {
        return {w+1, b};
    }
  };
  
  int n;
  vector<vector<int>> to;
  vector<vector<DP>> dp;
  vector<DP> ans;
  Rerooting(int n=0):n(n),to(n),dp(n),ans(n) {}
  void addEdge(int a, int b) {
    to[a].push_back(b);
    to[b].push_back(a);
  }
  void init() {
    dfs(0);
    bfs(0);
  }

  DP dfs(int v, int p=-1) {
    DP dpSum;
    dp[v] = vector<DP>(to[v].size());
    rep(i,to[v].size()) {
      int u = to[v][i];
      if (u == p) continue;
      dp[v][i] = dfs(u,v);
      dpSum = dpSum + dp[v][i];
    }
    return dpSum.addRoot();
  }
  void bfs(int v, const DP& dpP=DP(), int p=-1) {
    int deg = to[v].size();
    rep(i,deg) if (to[v][i] == p) dp[v][i] = dpP;

    vector<DP> dpSumL(deg+1);
    rep(i,deg) dpSumL[i+1] = dpSumL[i] + dp[v][i];
    vector<DP> dpSumR(deg+1);
    for (int i = deg-1; i >= 0; --i)
      dpSumR[i] = dpSumR[i+1] + dp[v][i];
    ans[v] = dpSumL[deg].addRoot();

    rep(i,deg) {
      int u = to[v][i];
      if (u == p) continue;
      DP d = dpSumL[i] + dpSumR[i+1];
      bfs(u, d.addRoot(), v);
    }
  }
};

int main()
{
    int n;
    cin >> n;
    Rerooting rt(n);
    rep(i,n-1){
        int u, v;
        cin >> u >> v;
        --u;--v;
        rt.addEdge(u,v);
    }
    rt.init();
    int f = 1e9;
    rep(i,n){
        f = min(f, rt.ans[i].b);
    }
    cout<<f<<endl;
    return 0;
}
0