首页 > 其他分享 >Count Valid Paths in a Tree

Count Valid Paths in a Tree

时间:2024-03-10 20:55:59浏览次数:25  
标签:Count Paths contains prime sum since number Valid path

Count Valid Paths in a Tree

There is an undirected tree with n nodes labeled from 1 to n. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree.

Return the number of valid paths in the tree.

A path (a, b) is valid if there exists exactly one prime number among the node labels in the path from a to b.

Note that:

  • The path (a, b) is a sequence of distinct nodes starting with node a and ending with node b such that every two adjacent nodes in the sequence share an edge in the tree.
  • Path (a, b) and path (b, a) are considered the same and counted only once.

 

Example 1:

Input: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]]
Output: 4
Explanation: The pairs with exactly one prime number on the path between them are: 
- (1, 2) since the path from 1 to 2 contains prime number 2. 
- (1, 3) since the path from 1 to 3 contains prime number 3.
- (1, 4) since the path from 1 to 4 contains prime number 2.
- (2, 4) since the path from 2 to 4 contains prime number 2.
It can be shown that there are only 4 valid paths.

Example 2:

Input: n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]]
Output: 6
Explanation: The pairs with exactly one prime number on the path between them are: 
- (1, 2) since the path from 1 to 2 contains prime number 2.
- (1, 3) since the path from 1 to 3 contains prime number 3.
- (1, 4) since the path from 1 to 4 contains prime number 2.
- (1, 6) since the path from 1 to 6 contains prime number 3.
- (2, 4) since the path from 2 to 4 contains prime number 2.
- (3, 6) since the path from 3 to 6 contains prime number 3.
It can be shown that there are only 6 valid paths.

 

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 <= ui, vi <= n
  • The input is generated such that edges represent a valid tree.

 

解题思路

  把简单路径按照经过的最高点进行分类,即根据路径两个端点的最近公共祖先来分类。对于以 $u$ 为根的子树,假设与其相邻的子节点为 $v_i$,由于经过 $u$ 的路径中必须恰好有一个质数节点,因此在子树 $v_i$ 中,含端点 $v_i$ 的路径中最多只能有一个质数节点。

  对此定义 $f(u, 0/1)$ 表示在子树 $u$ 中含端点 $u$ 的路径中恰好有 $0/1$ 个质数节点的数量。当 $u$ 是质数节点时,有 $\displaylines{\begin{cases} f(u,0) = 0 \\ f(u,1) = 1 + \sum{f(v_i,0)} \end{cases}}$。当 $u$ 不是质数节点时,有 $\displaylines{\begin{cases} f(u,0) = 1 + \sum{f(v_i,0)} \\ f(u,1) = \sum{f(v_i,1)} \end{cases}}$。

  再考虑两个端点的最近公共祖先是 $u$ 且经过恰好一个质数节点的简单路径的数量。如果 $u$ 是质数节点,则分成两个部分,一个是端点含 $u$ 的,对应的数量是 $\sum{f(v_i,0)}$。另一个两个端点来自不同的子树 $v_i$,对应的数量是 $\sum{f(v_i,0) \sum\limits_{j>i}{f(v_j,0)}}$。如果 $u$ 不是质数节点,也分成两个部分,一个是端点含 $u$ 的,对应的数量是 $\sum{f(v_i,1)}$。另一个两个端点来自不同的子树 $v_i$,对应的数量是 $\sum{f(v_i,1) \sum\limits_{j \ne i}{f(v_j,0)}}$。

  AC 代码如下,时间复杂度为 $O(n)$:

class Solution {
public:
    long long countPaths(int n, vector<vector<int>>& edges) {
        vector<vector<int>> g(n + 1);
        for (auto &p : edges) {
            g[p[0]].push_back(p[1]);
            g[p[1]].push_back(p[0]);
        }
        vector<int> primes;
        vector<bool> vis(n + 1);
        vis[1] = true;
        for (int i = 2; i <= n; i++) {
            if (!vis[i]) primes.push_back(i);
            for (int j = 0; primes[j] * i <= n; j++) {
                vis[primes[j] * i] = true;
                if (i % primes[j] == 0) break;
            }
        }
        vector<vector<int>> f(n + 1, vector<int>(2));
        long long ans = 0;
        function<void(int, int)> dfs = [&](int u, int p) {
            int s0 = 0, s1 = 0;
            for (auto &v : g[u]) {
                if (v == p) continue;
                dfs(v, u);
                s0 += f[v][0];
                s1 += f[v][1];
            }
            if (!vis[u]) {
                f[u][0] = 0;
                f[u][1] = s0 + 1;
                ans += s0;
                for (auto &v : g[u]) {
                    if (v == p) continue;
                    s0 -= f[v][0];
                    ans += 1ll * f[v][0] * s0;
                }
            }
            else {
                f[u][0] = s0 + 1;
                f[u][1] = s1;
                ans += s1;
                for (auto &v : g[u]) {
                    if (v == p) continue;
                    ans += 1ll * f[v][1] * (s0 - f[v][0]);
                }
            }
        };
        dfs(1, -1);
        return ans;
    }
};

标签:Count,Paths,contains,prime,sum,since,number,Valid,path
From: https://www.cnblogs.com/onlyblues/p/18064769

相关文章

  • Memberinfo call generic method System.InvalidOperationException: 'Late bound op
    staticvoidMain(string[]args){GenericMethod();LogInfo();}staticvoidGenericMethod(){MethodInfomi=typeof(Program).GetMethod("Echo");Console.WriteLine(mi.IsGenericMethodDefinition);Console.WriteLine(mi.Invoke(......
  • spring - mvc - @Valid
    自定义验证创建自定义验证器需要推出我们自己的注释并在我们的模型中使用它来强制执行验证规则。因此,让我们创建自定义验证器来检查电话号码。电话号码必须是至少8位数字,但不超过11位数字。1.新注释让我们创建一个新的@interface来定义我们的注释:@Documented@Constrain......
  • ABC221H Count Multiset
    [ABC221H]CountMultiset以下内容多引用自[1]对应的文章分拆数表示将正整数\(N\)拆成若干正整数和的方案数\(P_N\),可以形式化的表示成以下方程的解的个数\[x_1+x_2+...+x_m=N,1\lex_1\lex_2\le...\lex_m\]其中我们通常将每个正整数\(x_i\)称......
  • Spring-@Validated-参数校验
    1.什么是javax.validationJSR303是一套JavaBean参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们JavaBean的属性上面(面向注解编程的时代),就可以在需要校验的时候进行校验了,在SpringBoot中已经包含在starter-web中,再其他项目中可以引用依赖,并自行......
  • Though Our Paths May Diverge(JSOI 2024 游记)
    Isn’titsupposedtobesunnynow?且当是JSOI2024的游记吧。省选前的精神状态处于一种微妙的平衡。确实也不断在给自己心理暗示,自己有省队水平,但是其实无论是哪边的模拟打得都属于比较稀烂的水平,有的时候真的是一题不会签不上到。跟不上zhy和黄色蜜蜂的节奏啊,大概就......
  • 运行时遇到Oracle错误1017 invalid username/password;login denied
    参考链接:https://answer.baidu.com/answer/land?params=7elCyy2%2BVQFLNLJM1h81dr5QZQQgc1gH3Jx0mKtGyC9iN883lLAjVKkqqFwgT9IkwDSCCV6LpBhAaZmXkqXteDsXxjanzrzpWVxBkZhfR3Unz5gw02%2BImYJ2Z%2Bvnm92UuArsoipr6J4Lg4wWW8llDohcXIR6bJhJl2%2Fy598QiTvvwPJAYShha1DQ3DoUCfGRi%2BD......
  • 记录一次WPF命令参数报错,InvalidCastException: T for DelegateCommand<T> is not an
    在使用WPF的时候对int或者bool类型进行绑定出现InvalidCastException:TforDelegateCommandisnotanobjectnorNullable.<ButtonWidth="200"Height="30"Content="按钮"Command="{BindingOpenCommand}"CommandParameter="{Binding......
  • VSTO:WinForms如何引用Ribbon.Invalidate
    问题描述:近期项目需要在VSTO插件中设计WinForms界面,该界面需要实现一个功能:当WinForms从外部应用中获取数据后,将其传递到editbox显示栏内。项目开发中遇到以下问题:WinForms中实例化Ribbon后,再引用其中的函数或Invalidate功能,在运行时会报错:System.NullReferenceException:“未将......
  • springboot集成报文验证组件validation
    1.引入validation的依赖jar<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId><version>3.2.3</version></dependency>2.请求报文增加字段的校验规则packa......
  • 2024-selenium-问题一:java.io.IOException: Invalid Status code=403 text=Forbidden
    问题截图:  问题分析: 参考网址:https://blog.csdn.net/weixin_46739493/article/details/134163739问题解决:1、chrome版本为:版本114.0.5735.199(正式版本);driver的版本为:114.0.5735.90; java-seleium版本为:4.0.0-rc-21<dependency>2<groupId>org.......