码迷,mamicode.com
首页 > 其他好文 > 详细

cf219d

时间:2015-04-04 21:01:44      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

树形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;
}
View Code

 

cf219d

标签:

原文地址:http://www.cnblogs.com/rainydays/p/4392781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!