zoukankan      html  css  js  c++  java
  • [HAOI2009]毛毛虫

    嘟嘟嘟

    如果把毛毛虫的毛都剃下去,那么就是求树的直径。现在加上毛,也可以仿照树的直径树形dp的做法。

    在dfs的时候开两个变量,分别维护以u为端点的最长链Max1和次长链Max2,然后像求树的直径那样更新即可。

    单开一个dp[u]表示在u是的最长链,这个最长链是包含u及其毛的,而上面的不包括,这样方便更新(否则就会像我一样因为多一根毛少一根毛调了半天)。

    然后每次用Max1 + Max2 + w[u] - 1更新ans。(w[u]是u的毛,不包含u)

     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 = 3e5 + 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 << 1) + (ans << 3) + 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, m, w[maxn];
    38 
    39 struct Edge
    40 {
    41   int nxt, to;
    42 }e[maxn << 1];
    43 int head[maxn], ecnt = -1;
    44 void addEdge(int x, int y)
    45 {
    46   e[++ecnt] = (Edge){head[x], y};
    47   head[x] = ecnt;
    48 }
    49 
    50 int dp[maxn], ans = 0;
    51 void dfs(int now, int _f)
    52 {
    53   int Max1 = 0, Max2 = 0; dp[now] = 1;
    54   for(int i = head[now], v; i != -1; i = e[i].nxt)
    55     {
    56       v = e[i].to;
    57       if(v == _f) continue;
    58       dfs(v, now);
    59       if(dp[v] > Max1) Max2 = Max1, Max1 = dp[v];
    60       else if(dp[v] > Max2) Max2 = dp[v];
    61       dp[now] = max(dp[now], dp[v] + w[now] - 1);
    62     }
    63   ans = max(ans, Max1 + Max2 + w[now] - 1);
    64 }
    65 
    66 int main()
    67 {
    68   Mem(head, -1);
    69   n = read(); m = read();
    70   for(int i = 1; i <= m; ++i)
    71     {
    72       int x = read(), y = read();
    73       w[x]++; w[y]++;
    74       addEdge(x, y); addEdge(y, x);
    75     }
    76   dfs(1, 0);
    77   write(ans), enter;
    78   return 0;
    79 }
    View Code
  • 相关阅读:
    js完成打印功能
    ajax的序列化表单提交
    SpringMVC学习记录
    拦截器学习记录
    SpringMVC的controller层的方法返回值
    Mybatis学习记录(3)
    Mybatis学习记录(2)
    Mybatis学习记录(1)
    02-操作系统必会问题
    01-“计算机网络”必会问题
  • 原文地址:https://www.cnblogs.com/mrclr/p/9909526.html
Copyright © 2011-2022 走看看