美团2017年CodeM大赛-初赛B轮 黑白树 (树形dp)
2024-09-05 08:58:58
大意: 给定树, 初始每个点全为白色, 点$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 '\n'
#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\n", ans);
}
最新文章
- [转] ImageView的android:adjustViewBounds属性
- SqlServer事务回滚(2)
- javascript表单操作方法
- 如何在CODESOFT中自定义删除文档备料
- Build类
- 小心DLL链接静态库时的内存错误
- 测试部署nginx
- 【算法】字符串匹配之Z算法
- REST Adapter实现SAP PI中的增强XML/JSON格式转换
- 【JAVA零基础入门系列】Day11 Java中的类和对象
- ios 访问隐私信息 info.plist 中的字段
- vue初尝试--新建项目
- 依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象
- 7.2.4 else与if配对
- input accept属性限制文件上传格式
- 认识SQL
- hdu 1542
- php7配置多线程
- Redis源代码剖析--对象object
- java 多线程12 : 无锁 实现CAS原子性操作----原子类