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

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →