zoukankan      html  css  js  c++  java
  • 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
    ", 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
    ", u, v));
            ret += dfs(u, v, add + (1 - w), re_add + w) + w;
        }
        re_num[u] = add - re_add;
        D(printf("%d %d
    ", 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
    ", 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
    ", 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
    ", 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;
    }
    View Code
  • 相关阅读:
    Linux shell(3)
    Linux shell 编写(2)
    Linux shell 编写(1)
    团队冲刺(一)
    峦码团队任务表
    电梯演讲&界面展示说明
    第一次小组会议——NABCD讨论
    开发项目&团队介绍
    Linux中查看各文件夹大小命令:du -h --max-depth=1
    shell脚本[] [[]] -n -z 的含义解析
  • 原文地址:https://www.cnblogs.com/rainydays/p/4392781.html
Copyright © 2011-2022 走看看