| Homs Collegiate Programming Contest 2026 |
|---|
| Закончено |
You are given a tree consisting of $$$N$$$ vertices numbered from $$$1$$$ to $$$N$$$. The tree has $$$N-1$$$ weighted edges, where the $$$i$$$-th edge connects vertices $$$u_i$$$ and $$$v_i$$$ and has a weight $$$w_i$$$ ($$$1 \le w_i \le M$$$).
Let $$$S$$$ be the set of all simple paths in the tree that contain at least one edge. A simple path can be uniquely identified by its unordered pair of distinct endpoints $$$(u, v)$$$ ($$$1 \le u \lt v \le N$$$). Thus, there are exactly $$$|S| = \frac{N(N-1)}{2}$$$ paths in the set $$$S$$$. Each path $$$x \in S$$$ can be viewed as a set of edges.
For any two paths $$$x, y \in S$$$, we denote $$$x \cap y$$$ as the set of edges that are common to both paths. We define a cost function $$$f(x, y)$$$ as follows:
$$$$$$f(x, y) = ( \sum_{e \in x \cap y} w_e ) \cdot \gcd_{e \in x \cap y}(w_e)$$$$$$
I.e.: the value of a function is the sum of the weights on the intersection path of $$$x$$$ and $$$y$$$ times the GCD of the weights on the intersection path of $$$x$$$ and $$$y$$$, where $$$\gcd(i, j)$$$ is the greatest common divisor of $$$i$$$ and $$$j$$$.
Your task is to calculate the total sum of $$$f(x, y)$$$ over all ordered pairs of paths $$$(x, y)$$$ from the set $$$S$$$.
Since the total sum can be very large, output it modulo $$$998244353$$$.
The first line of the input contains a single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases.
The description of the test cases follows.
The first line of each test case contains two space-separated integers $$$N$$$ ($$$1 \le N \le 10^5$$$) and $$$M$$$ ($$$1 \le M \le 10^5$$$) — the number of vertices in the tree and the maximum possible edge weight.
Each of the next $$$N-1$$$ lines contains three space-separated integers $$$u_i$$$, $$$v_i$$$, and $$$w_i$$$ ($$$1 \le u_i, v_i \le N$$$, $$$u_i \neq v_i$$$, $$$1 \le w_i \le M$$$) — meaning there is an edge between vertices $$$u_i$$$ and $$$v_i$$$ with weight $$$w_i$$$.
It is guaranteed that the given edges form a valid tree, and the sum of $$$N$$$ and the sum of $$$M$$$ over all test cases does not exceed $$$10^5$$$.
For each test case, print a single integer — the total sum of $$$f(x, y)$$$ for all ordered pairs of distinct paths $$$(x, y)$$$, modulo $$$998244353$$$.
34 101 2 42 3 63 4 85 151 2 51 3 72 4 32 5 93 201 2 22 3 3
904208044
In the third test case, the tree consists of $$$N = 3$$$ vertices and has two weighted edges: $$$(1, 2)$$$ with weight $$$2$$$, and $$$(2, 3)$$$ with weight $$$3$$$.
There are exactly $$$|S| = \frac{3 \cdot (3 - 1)}{2} = 3$$$ simple paths containing at least one edge:
We calculate the function $$$f(x, y) = \left(\sum_{e \in x \cap y} w_e\right) \cdot \gcd_{e \in x \cap y}(w_e)$$$ for all $$$3 \times 3 = 9$$$ ordered pairs of paths:
Summing these values together gives: $$$$$$4 + 9 + 5 + 4 + 4 + 9 + 9 + 0 + 0 = 44$$$$$$ Thus, the total sum for the third testcase is $$$44$$$.
| Название |
|---|


