Game of Stones
InterviewTime limit1sMemory limit128 MB
Given a directed acyclic graph with stones on nodes, two players alternately slide one stone along an edge; decide whether the first player wins.
- Level
Hard8 of 10
- Topics
- Game theory, Graph, Dynamic programming, Topological sort
- Solved
- No attempts yet
Problem
Captain America has just caught up with the supervillain Loki to retrieve the Cosmic Cube, and the two are about to begin one of their epic battles. Loki, tired of getting beaten, instead challenges Captain America to a battle of wits, and Captain America — confident in the abilities of his trusty sidekick (that is, you) — accepts.
Loki explains the game. He draws an acyclic directed graph (as shown in the figure) and places a number of stones on its nodes. The two players take turns, each moving one stone from a node to one of that node's out-neighbors along a directed edge. For example, in either case below the stone on node 0 can be moved to node 1, but a stone can never be moved from node 1 to node 0. Multiple stones may sit on the same node at the same time. A player who cannot move any stone on their turn loses the game — and the Cosmic Cube.
Call a node with no outgoing edges a sink node. A move can always be made while at least one stone sits on a non-sink node, so the aim is to be the player who moves the last stone off a non-sink node.

Figure: (1) In the first case the moves are forced (there is no choice) and Player 1 wins. (2) In the second case, no matter what Player 1 does on the first move, Player 2 can win.
Loki lets you choose whether to move first or second. Work out the right choice: decide whether the player who moves first wins under optimal play.
Input
The input consists of several test cases. Each test case begins with a line containing two integers and : the number of nodes and the number of edges (, ). The next line contains the edges, each given by two integers and — the start and end node of a directed edge (nodes are labeled from to ). The following line contains integers , where is the number of stones initially placed on node (). The input is terminated by a line containing 0 0, which must not be processed.
Output
For each test case, output a single line containing First if the player who moves first wins, or Second if the player who moves second wins, assuming optimal play by both sides.