From a23883a88d615115e80e4aca4d1b902751c5561b Mon Sep 17 00:00:00 2001 From: cyp0633 Date: Mon, 16 Aug 2021 16:41:01 +0800 Subject: [PATCH] =?UTF-8?q?CSP=205-10=20=E6=A0=91=E7=9A=84=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CSP-Training/5/10-tree.cpp | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 CSP-Training/5/10-tree.cpp diff --git a/CSP-Training/5/10-tree.cpp b/CSP-Training/5/10-tree.cpp new file mode 100644 index 0000000..3e5f705 --- /dev/null +++ b/CSP-Training/5/10-tree.cpp @@ -0,0 +1,52 @@ +//树的优化 | CF682C Alyona and the Tree +#include +#include +using namespace std; +int head[100001], nxt[100000], to[100000], val[100001], weight[100000]; +int n, preserveCount; +void dfs(int currPos, int dist); +void insert(const int &source, const int &dest, const int &wt); +int main() +{ + int parentTemp, weightTemp; + scanf("%d", &n); + for (int i = 1; i <= n; i++) + { + scanf("%d", &val[i]); + } + for (int i = 1; i < n; i++) //从第2号结点开始输入父节点和边权 + { + scanf("%d %d", &parentTemp, &weightTemp); + insert(parentTemp, i + 1, weightTemp); //只需要加一条,这个是有向的 + } + dfs(1, 0); + printf("%d", n - preserveCount); + return 0; +} +void dfs(int currPos, int dist) +{ + if (dist > val[currPos]) + { + return; + } + preserveCount++; + for (int i = head[currPos]; i != 0; i = nxt[i]) + { + if (dist > 0) + { + dfs(to[i], dist + weight[i]); + } + else + { + dfs(to[i], weight[i]); + } + } + return; +} +void insert(const int &source, const int &dest, const int &wt) +{ + nxt[dest - 1] = head[source]; + head[source] = dest - 1; + to[dest - 1] = dest; + weight[dest - 1] = wt; +} \ No newline at end of file