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. Constraints 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;
S.erase(x);
} else {
h1 = (h1 + toPower(arg1, x, mod1)) % mod1;
h2 = (h2 + toPower(arg2, x, mod2)) % mod2;
S.insert(x);
}
}
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++)
neigh[i].clear();
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));
}
S.clear();
M.clear(); tot = 0;
res = 0;
Traverse(1, 0, 0, 0);
printf("%lld\n", res);
}
return 0;
}
In Python3 :
#!/bin/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):
print(space,self.node_val,self.edge_weight)
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])
else:
new_prev_lst = pre_lst.union([self.edge_weight])
acc_lst.append(new_prev_lst)
for c_node in self.children:
c_node.list_weights(acc_lst,new_prev_lst)
def add_node(self,n1,n2,edge_weight):
if self.node_val == n1:
self.children.append(Node(n2,edge_weight))
return True
elif self.node_val == n2:
self.children.append(Node(n1,edge_weight))
return True
else:
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):
self.root.add_node(n1,n2,edge_weight)
def print_tree(self):
self.root.print_node("")
def list_nodes(self):
lst_lst = []
pre_lst = set()
lst_lst.append(pre_lst)
for c_node in self.root.children:
c_node.list_weights(lst_lst,pre_lst)
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
else:
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])
else:
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')
fptr.close()
View More Similar Problems
Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →Square-Ten Tree
The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the
View Solution →Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a
View Solution →Jenny's Subtrees
Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .
View Solution →Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →