cf219d

树形dp

#include <cstdio>
#include <vector>
using namespace std;

#define D(x) 

const int INF = 0x3f3f3f3f;
const int MAX_N = (int)(2e5) + 10;

int n;
vector<pair<int, int> > edge[MAX_N];
int re_num[MAX_N];
vector<int> ans_vec;

int dfs(int father, int u, int add, int re_add)
{
    D(printf("u=%d\n", u));
    int ret = 0;
    for (int i = 0; i < (int)edge[u].size(); i++)
    {
        int v = edge[u][i].first;
        int w = edge[u][i].second;
        if (v == father)
        {
            continue;
        }
        D(printf("u=%d, v=%d\n", u, v));
        ret += dfs(u, v, add + (1 - w), re_add + w) + w;
    }
    re_num[u] = add - re_add;
    D(printf("%d %d\n", u, ret));
    return ret;
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i < n; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        edge[a].push_back(make_pair(b, 0));
        edge[b].push_back(make_pair(a, 1));
        D(printf("%d %d\n", a, b));
    }
    fill_n(re_num, n + 1, 0);
    int ans = dfs(-1, 1, 0, 0);
    ans_vec.push_back(1);
    int root_ans = ans;
    D(printf("%d\n", root_ans));
    for (int i = 2; i <= n; i++)
    {
        int temp = re_num[i] + root_ans;
        if (temp == ans)
        {
            ans_vec.push_back(i);
        }
        if (temp < ans)
        {
            ans = temp;
            ans_vec.clear();
            ans_vec.push_back(i);
        }
    }
    printf("%d\n", ans);
    for (int i = 0; i < (int)ans_vec.size(); i++)
    {
        printf("%d", ans_vec[i]);
        if (i != (int)ans_vec.size() - 1)
            putchar(‘ ‘);
    }
    puts("");
    return 0;
}

时间: 2024-12-30 02:12:04

cf219d的相关文章

cf219d 基础换根法

/*树形dp换根法*/ #include<bits/stdc++.h> using namespace std; #define maxn 200005 struct Edge{int to,nxt,flag;}edge[maxn<<1]; int root,n,s,t,head[maxn],tot,dp[maxn]; void init(){ memset(head,-1,sizeof head); tot=0; } void addedge(int u,int v,int fl