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
Reverse a doubly linked list
This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.
View Solution →Tree: Preorder Traversal
Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's
View Solution →Tree: Postorder Traversal
Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the
View Solution →Tree: Inorder Traversal
In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func
View Solution →Tree: Height of a Binary Tree
The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary
View Solution →Tree : Top View
Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.
View Solution →