Codeforces Round #821 (Div. 2)

题目链接

Codeforces Round #821 (Div. 2)

D.Fake Plastic Trees

t 组数据,每组给定一个 n 个结点的树, 根为 1 ,给定 2,3,,n 的父结点 p2,p3,,pn 。再给出每个点权值 ai 的范围 [li,ri]

初始每个点的权值均为 0 。每次操作可以选择从 1 开始的树上路径 b1,b2,,bk (不一定要在叶子处结束),将 abi 加上 ci ,其中 {ci} 是一个 非负单调非减整数 数列。

问至少多少次操作,可以令所有点点权均在 [li,ri] 范围内。

1t1000,2n2×105,n2×105,1pi<i,1liri109

解题思路

贪心

贪心策略:从叶子节点开始尽量消最多,关键在于 dfs 的写法

  • 时间复杂度:O(n)

代码

// Problem: D. Fake Plastic Trees // Contest: Codeforces - Codeforces Round #800 (Div. 2) // URL: https://codeforces.com/contest/1694/problem/D // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> // #define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } const int N=2e5+5; int t,n,res,b[N]; PII a[N]; bool v[N]; vector<int> adj[N]; void dfs(int x) { LL s=0; for(int y:adj[x]) { dfs(y); s+=b[y]; } if(a[x].fi>s)res++,b[x]=a[x].se; else b[x]=min(1ll*a[x].se,s); } int main() { for(cin>>t;t;t--) { cin>>n; for(int i=1;i<=n;i++)adj[i].clear(),b[i]=0; for(int i=2;i<=n;i++) { int x;cin>>x; adj[x].pb(i); } for(int i=1;i<=n;i++)cin>>a[i].fi>>a[i].se; res=0; dfs(1); cout<<res<<'\n'; } return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/16691283.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(136)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-09-13 EOJ Monthly 2021.9
点击右上角即可分享
微信分享提示