zoukankan      html  css  js  c++  java
  • [POI2008]STA-Station

    嘟嘟嘟

    一道树形dp题。

    令dp[u]表示以u为根时所有点的深度之和。考虑u到他的一个子节点v时答案的变化,v子树以外的点的深度都加1,v子树以内的点的深度都减1,所以dp[v] = dp[u] + (n - siz[v]) - siz[v]。于是dp式就搞出来了。

    所以两边dfs,第一遍求siz和dp[1],第二遍更新答案。

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cmath>
     4 #include<algorithm>
     5 #include<cstring>
     6 #include<cstdlib>
     7 #include<cctype>
     8 #include<vector>
     9 #include<stack>
    10 #include<queue>
    11 using namespace std;
    12 #define enter puts("") 
    13 #define space putchar(' ')
    14 #define Mem(a, x) memset(a, x, sizeof(a))
    15 #define rg register
    16 typedef long long ll;
    17 typedef double db;
    18 const int INF = 0x3f3f3f3f;
    19 const db eps = 1e-8;
    20 const int maxn = 1e6 + 5;
    21 inline ll read()
    22 {
    23     ll ans = 0;
    24     char ch = getchar(), last = ' ';
    25     while(!isdigit(ch)) {last = ch; ch = getchar();}
    26     while(isdigit(ch)) {ans = ans * 10 + ch - '0'; ch = getchar();}
    27     if(last == '-') ans = -ans;
    28     return ans;
    29 }
    30 inline void write(ll x)
    31 {
    32     if(x < 0) x = -x, putchar('-');
    33     if(x >= 10) write(x / 10);
    34     putchar(x % 10 + '0');
    35 }
    36 
    37 int n, ans = 1;
    38 struct Edge
    39 {
    40     int nxt, to;
    41 }e[maxn << 1];
    42 int head[maxn], ecnt = 0;
    43 void addEdge(int x, int y)
    44 {
    45     e[++ecnt] = (Edge){head[x], y};
    46     head[x] = ecnt;
    47 }
    48 
    49 int siz[maxn], dep[maxn];
    50 ll dp[maxn];
    51 void dfs1(int now, int f)
    52 {
    53     siz[now] = 1;
    54     for(int i = head[now]; i; i = e[i].nxt)
    55     {
    56         if(e[i].to == f) continue;
    57         dep[e[i].to] = dep[now] + 1;
    58         dp[1] += dep[e[i].to];
    59         dfs1(e[i].to, now);
    60         siz[now] += siz[e[i].to];
    61     }
    62     
    63 }
    64 void dfs2(int now, int f)
    65 {
    66     for(int i = head[now]; i; i = e[i].nxt)
    67     {
    68         if(e[i].to == f) continue;
    69         dp[e[i].to] = dp[now] + n - (siz[e[i].to] << 1);
    70         if(dp[e[i].to] > dp[ans]) ans = e[i].to;
    71         dfs2(e[i].to, now);
    72     }
    73 }
    74 
    75 int main()
    76 {
    77     n = read();
    78     for(int i = 1; i < n; ++i)
    79     {
    80         int x = read(), y = read();
    81         addEdge(x, y); addEdge(y, x);
    82     }
    83     dfs1(1, 0); dfs2(1, 0);
    84     write(ans); enter;
    85     return 0;
    86 }
    View Code
  • 相关阅读:
    JZOJ 2548. 【NOIP2011模拟9.4】最大正方形
    JZOJ 3532. 【NOIP2013提高组day1】转圈游戏
    网络流模板 dinic
    1433: [ZJOI2009]假期的宿舍
    JZOJ 1285. 奶酪厂
    JZOJ 1284. 病毒
    SpringMVC路径匹配规则源码
    RESTful设计风格下SpringMVC的URI设计性能问题
    递归查询mysql数据库设计
    java定时任务调度
  • 原文地址:https://www.cnblogs.com/mrclr/p/9808298.html
Copyright © 2011-2022 走看看