• 美团2017年CodeM大赛-初赛B轮 黑白树 (树形dp)


    大意: 给定树, 初始每个点全为白色, 点$i$有权值$k_i$, 表示选择$i$后, 所有距离$i$小于$k_i$的祖先(包括i)会变为黑色, 求最少选多少个点能使所有点变为黑色.

    链上情况的话, 直接从链头开始做一次线性dp就行了, 但是显然不能拓展到树上情况. 

    正解是从叶子往上贪心划分, 若当前点$x$为白色, 则从$x$子树内选择一个$y$, 满足$k[y]-dis(x,y)$最大, 这个显然可以用树形dp在O(n)时间求出.

    #include <iostream>
    #include <sstream>
    #include <algorithm>
    #include <cstdio>
    #include <math.h>
    #include <set>
    #include <map>
    #include <queue>
    #include <string>
    #include <string.h>
    #include <bitset>
    #define REP(i,a,n) for(int i=a;i<=n;++i)
    #define PER(i,a,n) for(int i=n;i>=a;--i)
    #define hr putchar(10)
    #define pb push_back
    #define lc (o<<1)
    #define rc (lc|1)
    #define mid ((l+r)>>1)
    #define ls lc,l,mid
    #define rs rc,mid+1,r
    #define x first
    #define y second
    #define io std::ios::sync_with_stdio(false)
    #define endl '
    '
    #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;})
    using namespace std;
    typedef long long ll;
    typedef pair<int,int> pii;
    const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f;
    ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
    ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
    ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
    inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}
    //head
    
    
    const int N = 1e6+10;
    int n, ans, fa[N], k[N];
    vector<int> g[N];
    
    int dfs(int x) {
    	int d = 0;
    	for (int y:g[x]) d=max(d,dfs(y));
    	k[fa[x]] = max(k[fa[x]], k[x]-1);
    	if (d>0) return d-1;
    	return ++ans, k[x]-1;
    }
    
    int main() {
    	scanf("%d", &n);
    	REP(i,2,n) {
    		scanf("%d", fa+i);
    		g[fa[i]].pb(i);
    	}
    	REP(i,1,n) scanf("%d", k+i);
    	dfs(1);
    	printf("%d
    ", ans);
    }
    
  • 相关阅读:
    SystemVerilog搭建测试平台---第一章:验证导论
    二线制I2C CMOS串行EEPROM续
    二线制I2C CMOS串行EEPROM
    Codeforces 777E:Hanoi Factory(贪心)
    2019HPU-ICPC-Training-1
    Codeforces 777B:Game of Credit Cards(贪心)
    Codeforces 777D:Cloud of Hashtags(暴力,水题)
    Codeforces 777C:Alyona and Spreadsheet(预处理)
    Codeforces 888D: Almost Identity Permutations(错排公式,组合数)
    Codeforces 888E:Maximum Subsequence(枚举,二分)
  • 原文地址:https://www.cnblogs.com/uid001/p/10925278.html
Copyright © 2020-2023  润新知