Neurotic Network
InterviewTime limit1sMemory limit256 MB
Evaluate the weighted sum from the leaves to the root of a tree and print FREAK OUT for an even result, else the value modulo 1,000,000,007.
- Level
Easy3 of 10
- Topics
- Tree, Dynamic programming, Math
- Solved
- No attempts yet
Problem
In this problem a neural net is a rooted tree with a weight on every edge. Signals cascade from the leaf nodes toward the root: each node computes an output value from its upstream neighbours and passes that value on to its single downstream neighbour. The output value of a node is the sum, over all of its upstream neighbours, of that neighbour's output value multiplied by the weight of the edge running from the neighbour into the node. A node with no upstream neighbour is a leaf, and a leaf always has 1 as its output. Every neural net in this problem has exactly one final output node, the root node.
A neural net sometimes goes haywire and becomes what is more commonly known as a neurotic network. Consider this your chance to start a second career in psychiatry. Someone has just walked in with a neurotic network in their head. If the output of their neural net is an even number, the person freaks out and sets fire to a kitten. Knowing ahead of time whether a given person is safe therefore matters. If the person is safe, print their neural output modulo 1,000,000,007. If you would not trust the person around kittens who are not wrapped in fire retardant, print the string FREAK OUT without the quotes.
Input
The first line contains , the number of test cases. Each test case begins with a line holding the integer , the number of nodes in the tree. The next line contains integers , where is the downstream neighbour of the node with ID . The line after that contains integers , where is the weight of the neural connection going out from the node with ID . The node with ID 0 is always the output node.
- The given graph is always a tree.
When both integer lines are empty. This is an I/O heavy problem, so read the input with a buffered reader.
Output
Print one line per test case. If the final value of the neural net's output node is even, print FREAK OUT without the quotes. Otherwise print that final value modulo 1,000,000,007.