Number Game on a Tree

Problem Statement :

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1   edges. Each edge  i has an integer weight, wi.

Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v  to construct a list of numbers. For example, in the diagram below, Andy constructs a list from the edge weights along the path ( 2, 6 ):

Andy then uses this list to play the following game with Lily:

Two players move in alternating turns, and both players play optimally (meaning they will not make a move that causes them to lose the game if some better, winning move exists).
Andy always starts the game by removing a single integer from the list.
During each subsequent move, the current player removes an integer less than or equal to the integer removed in the last move.
The first player to be unable to move loses the game.

Input Format

The first line contains a single integer, , denoting the number of games. The subsequent lines describe each game in the following format:

The first line contains an integer, n, denoting the number of nodes in the tree.
Each line  i of the n - 1 subsequent lines contains three space-separated integers describing the respective values of , ui, viand wi  for the  edge connecting nodes ui and vi with weight wi.


1  <=  g  <=  10
1  <=  n   <=  5 x 10^5
1  <=  ui , vi  <=  n
0  <=  wi  <=  10^9
Sum of  n over all games does not exceed 5 x 10^5

Output Format

For each game, print an integer on a new line describing the number of unordered pairs Andy can choose to construct a list that allows him to win the game.

Solution :


                            Solution in C :

In    C++  :

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#pragma comment(linker, "/STACK:16000000")
using namespace std;

typedef pair <int, int> ii;
typedef long long ll;

const int mod1 = 1000000007;
const int mod2 = 1000000009;
const int arg1 = 37;
const int arg2 = 1000007;
const int Maxn = 500005;

int g;
int n;
vector <ii> neigh[Maxn];
set <int> S;
map <ii, int> M;
int tot;
ll res;

int toPower(int a, int p, int mod)
    int res = 1;
    while (p) {
        if (p & 1) res = ll(res) * a % mod;
        p >>= 1; a = ll(a) * a % mod;
    return res;

void Switch(int &h1, int &h2, int x)
    if (S.find(x) != S.end()) {
        h1 = (h1 - toPower(arg1, x, mod1) + mod1) % mod1;
        h2 = (h2 - toPower(arg2, x, mod2) + mod2) % mod2;
    } else {
        h1 = (h1 + toPower(arg1, x, mod1)) % mod1;
        h2 = (h2 + toPower(arg2, x, mod2)) % mod2;

void Traverse(int v, int p, int h1, int h2)
    res += tot - M[ii(h1, h2)]; M[ii(h1, h2)]++; tot++;
    for (int i = 0; i < neigh[v].size(); i++) {
        ii u = neigh[v][i];
        if (u.first == p) continue;
        Switch(h1, h2, u.second);
        Traverse(u.first, v, h1, h2);
        Switch(h1, h2, u.second);

int main(){
    scanf("%d", &g);
    while (g--) {
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
        for (int i = 0; i < n - 1; i++) {
            int a, b, c; scanf("%d %d %d", &a, &b, &c);
            neigh[a].push_back(ii(b, c));
            neigh[b].push_back(ii(a, c));
        M.clear(); tot = 0;
        res = 0;
        Traverse(1, 0, 0, 0);
        printf("%lld\n", res);
    return 0;

In   Python3  :


import os
import sys
from itertools import combinations
from collections import Counter

class Node:
    def __init__(self,v,edge_weight=-1):
        self.node_val = v
        self.edge_weight = edge_weight
        self.children = []
    def print_node(self,space):
        for c_node in self.children:
            c_node.print_node(space+" ")
    def list_weights(self,acc_lst,pre_lst):
        if self.edge_weight in pre_lst:
            # print('executed')
            new_prev_lst =  pre_lst - set([self.edge_weight])
            new_prev_lst = pre_lst.union([self.edge_weight])
        for c_node in self.children:
    def add_node(self,n1,n2,edge_weight):
        if self.node_val == n1:
            return True
        elif self.node_val == n2:
            return True
            for c_node in self.children:
                if c_node.add_node(n1,n2,edge_weight):
                    return True
        return False
class Tree:
    def __init__(self,root_value):
        self.root = Node(root_value)
    def add_node(self,n1,n2,edge_weight):
    def print_tree(self):
    def list_nodes(self):
        lst_lst = []
        pre_lst = set()
        for c_node in self.root.children:
        return lst_lst
# Complete the numberGameOnATree function below.
def numberGameOnATree(n, edges):
    # tree = Tree(1)
    # for e in edges:
    #     n1, n2, child_weight = e
    #     tree.add_node(n1, n2, child_weight)
    total = (n * (n-1))//2
    # ordered_lst = tree.list_nodes()
    # test_set = set([10**1])
    # test_set.union(set([10**9]))
    ordered_lst = [None]*n
    node_available = [0]*n
    ordered_lst[0] = frozenset()
    node_available[0] = 1
    for e in edges:
        n1, n2, child_weight = e
        # child_weight = 10**9 - child_weight
        # print(n1,node_ind,n1 in node_ind.keys())
        if node_available[n1-1] == 1:
            src = n1-1
            dst = n2-1
            src = n2-1
            dst = n1-1
        # if n1 in node_ind.keys() and not n2 in node_ind.keys():
        #     src = node_ind[n1]
        #     dst = n2
        # elif n2 in node_ind.keys() and not n1 in node_ind.keys():
        #     src = node_ind[n2]
        #     dst = n1
        # node_ind[dst]=node_cnt
        # node_cnt+=1
        # continue
        # else:
            # return 0
        # print(src,dst)
        prev_set = ordered_lst[src]
        # new_set = set()
        if child_weight in prev_set:
            new_set =  prev_set - frozenset([child_weight])
            sing_item_set = frozenset([child_weight])
            # if len(sing_item_set)>1:
                # return 0
            new_set = prev_set.union(sing_item_set)
            # new_set = set()
        ordered_lst[dst] = new_set
        node_available[dst] = 1
    # print(ordered_lst)
    # ordered_lst_cnt  = Counter([frozenset(s) for s in ordered_lst])
    ordered_lst_cnt  = Counter(ordered_lst)
    loss = 0
    for c in ordered_lst_cnt.values():
        loss += (c * (c-1))//2
    return total - loss 
    # win_combination = 0
    # for t in combinations(ordered_lst,2):
    #     if t[0] == t[1]:
    #         continue
    #     win_combination+=1
    # return win_combination

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    g = int(input())

    for g_itr in range(g):
        n = int(input())

        edges = []

        for _ in range(n-1):
            edges.append(list(map(int, input().rstrip().split())))

        result = numberGameOnATree(n, edges)

        fptr.write(str(result) + '\n')


View More Similar Problems


This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →