zoukankan      html  css  js  c++  java
  • Codeforces 219D. Choosing Capital for Treeland (树dp)

    题目链接:http://codeforces.com/contest/219/problem/D

    树dp

     1 //#pragma comment(linker, "/STACK:102400000, 102400000")
     2 #include <algorithm>
     3 #include <iostream>
     4 #include <cstdlib>
     5 #include <cstring>
     6 #include <cstdio>
     7 #include <vector>
     8 #include <cmath>
     9 #include <ctime>
    10 #include <list>
    11 #include <set>
    12 #include <map>
    13 using namespace std;
    14 typedef long long LL;
    15 typedef pair <int, int> P;
    16 const int N = 2e5 + 5;
    17 struct Edge {
    18     int next, to, cost;
    19 }edge[N << 1];
    20 int head[N], tot, d[N], ans1[N], ans[N];
    21 int res[N];
    22 
    23 inline void add_edge(int u, int v, int c) {
    24     edge[tot].next = head[u];
    25     edge[tot].to = v;
    26     edge[tot].cost = c;
    27     head[u] = tot++;
    28 }
    29 
    30 void dfs1(int u, int p) {
    31     d[u] = 1;
    32     ans1[u] = 0;
    33     for(int i = head[u]; ~i; i = edge[i].next) {
    34         int v = edge[i].to;
    35         if(v == p)
    36             continue;
    37         dfs1(v, u);
    38         d[u] += d[v];
    39         ans1[u] += edge[i].cost + ans1[v];
    40     }
    41 }
    42     
    43 void dfs2(int u, int p) {
    44     ans[u] += ans1[u];
    45     for(int i = head[u]; ~i; i = edge[i].next) {
    46         int v = edge[i].to;
    47         if(v == p)
    48             continue;
    49         ans[v] = ans[u] - ans1[v] - edge[i].cost + !edge[i].cost;
    50         dfs2(v, u);
    51     }
    52 }
    53 
    54 int main()
    55 {
    56     memset(head, -1, sizeof(head));
    57     int n, u, v;
    58     scanf("%d", &n);
    59     for(int i = 1; i < n; ++i) {
    60         scanf("%d %d", &u, &v);
    61         add_edge(u, v, 0);
    62         add_edge(v, u, 1);
    63     }
    64     dfs1(1, -1);
    65     dfs2(1, -1);
    66     int Min = N, cnt = 0;
    67     for(int i = 1; i <= n; ++i) {
    68         Min = min(Min, ans[i]);
    69     }
    70     for(int i = 1; i <= n; ++i) {
    71         if(ans[i] == Min) {
    72             res[++cnt] = i;
    73         }
    74     }
    75     printf("%d
    ", Min);
    76     sort(res + 1, res + cnt + 1);
    77     for(int i = 1; i <= cnt; ++i) {
    78         printf("%d%c", res[i], i == cnt ? '
    ': ' ');
    79     }
    80     return 0;
    81 }
  • 相关阅读:
    配置Robot Framework 环境时如何查看wxPython是否成功安装
    win10系统同时安装python2.7和python3.6
    Python 统计不同url svn代码变更数
    JavaWeb之 Servlet执行过程 与 生命周期
    JavaWeb之Servlet:请求 与 响应
    webservice(基础)
    通过反射,给对象之间赋值
    用反射获取类中的属性值
    tree树形
    破解weblogic(数据库)密码
  • 原文地址:https://www.cnblogs.com/Recoder/p/5934023.html
Copyright © 2011-2022 走看看