Given a tree with N nodes. Two players A and B start from node 1 and node N respectively. A can visit all the adjacent nodes to the nodes already visited by A but can not visit any nodes which is already visited by B and similary for B also.
The player who visits more cities win. Find the player who wins if they both play optimally.
Input: Output: A wins
Approach: The optimal solution is that both the Player starts visiting the nodes which lie in the path connecting node 1 and node N. This is because one player cannot visit the nodes already visited by another player so each player will try to limit the number of nodes that can be visited by another player. Then it will be easy to count the number of nodes that can be visited by each player and find out the winner.
The DFS will be use to find out the path between two nodes and mark them one by one like 1 or 2, 1 for A and 2 for B and then mark all the adjacent unvisited nodes with the respective value and then calculate the count of nodes of A and B.
Below is the implementation of the above approach:
- Print levels with odd number of nodes and even number of nodes
- Check if two nodes are on same path in a tree
- Check if two nodes are in same subtree of the root node
- Check if two nodes in a Binary Tree are siblings
- Check if two nodes are cousins in a Binary Tree
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check sum of Covered and Uncovered nodes of Binary Tree
- Given a n-ary tree, count number of nodes which have more number of children than parents
- Calculate number of nodes in all subtrees | Using DFS
- Print all the levels with odd and even number of nodes in it | Set-2
- Count the nodes whose sum with X is a Fibonacci number
- Number of Unicolored Paths between two nodes
- Number of special nodes in an n-ary tree
- Number of nodes greater than a given value in n-ary tree
- Count the number of non-reachable nodes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : mohit kumar 29