#P5563. [Celeste-B] No More Running

[Celeste-B] No More Running

Description

Crystals are scattered all along the road to the summit.

In a cluster of crystals, Madeline finds an unusual crystal cave, with colorful gems embedded inside.

After observing, Madeline realizes that these gems form a wonderful mechanism: as long as the gems collect enough magic power, the mechanism can be activated and the Crystal Heart can be obtained.

More specifically, in this huge cave there are nn gems. Each gem is embedded in a tree structure that is exactly the same in shape but independent from the others. To be even more specific, there are nn identical tree structures TT in the cave. The tree structure TT has nn nodes, and the ii-th gem is embedded at node ii of the ii-th tree structure TT.

Madeline can push a gem so that it slides along the tree. After the gem passes through an edge, that edge will be closed, and the magic power stored on that edge will be accumulated into the gem. (Reminder: the tree structures containing these nn gems are independent. This means that closing an edge in one tree will not cause the same edge to be closed in other trees.)

A gem has a limit on how much magic power it can store. More specifically, each gem can store only modmod magic power. Once it exceeds this upper bound, the magic power overflows. You can treat this as taking the stored magic power modulo modmod.

Madeline wants to know the maximum magic power that the gem embedded at each vertex can store in the end. Can you help her?

Input Format

The first line contains two integers nn, modmod, representing the number of nodes in the tree structure and modmod.

The next n1n-1 lines each contain three integers u,v,wu, v, w, describing an undirected edge in the tree structure that connects uu and vv with energy value ww (0w<mod0 \leq w < mod). (Note that closing an edge works in both directions, which means you cannot go back along that edge.)

It is guaranteed that these edges form a tree.

Output Format

Output nn lines, each line containing nn integers. The ii-th integer represents the maximum magic power that the gem embedded at vertex ii can store.

5 16
1 2 13
2 3 15
3 4 7
3 5 3

15
15
15
10
15

Hint

Image failed to load

In the "Special Convention", "a chain" means that the ii-th edge of the tree structure connects node ii and node i+1i+1.

For all testdata, 0w<mod0 \leq w < mod.

It is guaranteed that all input edges form a tree.

For test points 11 to 66, the time limit is 1s1s.

For test points 77 to 1212, the time limit is 2s2s.

For test points 1313 to 2020, the time limit is 3s3s.

Translated by ChatGPT 5