Root the tree at vertex and index the flower shops from to . Let be the bitmask of shops in the subtree of . Obtain every mask in time by OR-ing child masks into parent masks.
After visiting a set of shops, the traversed vertices are precisely the union of the root-to-shop paths for shops in . Hence the number of flowers picked is . Exactly flowers have been sold, so the prefix set is feasible if and only if .
Define and . Using SOS DP, compute . Then , where XOR takes the complement of within the bits.
Let be the number of successful orders that visit precisely the shops of . Set . For nonempty :
The summands partition orders by the last shop . Take every sum modulo . The answer is .
Time complexity is , space complexity is , and the total flower count is at most , which fits in signed 64-bit arithmetic.
Solution written by GPT6