Heavy Light White Falcon


Problem Statement :


Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem.

You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries:

"1 u x" assign x to the value of the node .
"2 u v" print the maximum value of the nodes on the unique path between u and v.


Input Format

First line consists of two integers seperated by a space: N and Q.
Following N - 1  lines consisting of two integers denotes the undirectional edges of the tree.
Following Q lines consist of the queries you are asked to operate.

Constraints

1  <=   N , Q , x  <=  50000

It is guaranteed that input denotes a connected tree with N nodes. Nodes are enumerated with 0-based indexing.


Output Format

For each second type of query print single integer in a single line, denoting the asked maximum value.



Solution :



title-img


                            Solution in C :

In   C++   :








#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 50010;

class node {
    
    public :
        int l, r, mx;
        node *left, *right;
    
        void update(int idx, int val) {
            if(l >= r) {
                mx = val;
                return;
            }        
            int mid = (l + r) / 2;
            (idx <= mid ? left : right)->update(idx, val);
            mx = max(left->mx, right->mx);
        }
    
        int query(int a, int b) {
            if(b < l or r < a) return 0;
            if(a <= l and r <= b) return mx;
            return max(left->query(a, b), right->query(a, b));
        }
    
        node(int _l, int _r) : 
            l(_l), r(_r), mx(0), left(NULL), right(NULL) {}
};

node* init(int l, int r) {
    node *p = new node(l, r);
    if(l < r) {
        int mid = (l + r) / 2;
        p->left = init(l, mid);
        p->right = init(mid+1, r);
    }
    return p;
}

vector<int> adj[N];
int n, q;

node* head[N];
vector<int> Path[N];
int sz[N], H[N], P[N], G[N], pos[N];

void dfs_init(int u, int p, int h) {
    P[u] = p;
    H[u] = h;
    sz[u] = 1;
    for(int v : adj[u]) {
        if(v == p) {
            continue;
        }
        dfs_init(v, u, h+1);
        sz[u] += sz[v];
    }
}
void dfs_HLD(int u) {
    Path[u].push_back(u);
    for(int i = 0;i < Path[u].size();i++) {
        int v = Path[u][i];
        G[v] = u;
        pos[v] = i;
        for(int vv : adj[v]) {
            if(vv == P[v]) continue;
            if(2*sz[vv] >= sz[v]) {
                Path[u].push_back(vv);
            }else {
                dfs_HLD(vv);
            }
        }
    }
    head[u] = init(0, Path[u].size() - 1);
}
int query(int u, int v) {
    int ans = 0;
    while(G[u] != G[v]) {
        if(H[G[u]] < H[G[v]]) {
            swap(u, v);
        }
        ans = max(ans, head[G[u]]->query(0, pos[u]));
        u = P[G[u]];
    }
    if(pos[u] > pos[v]) {
        swap(u, v);
    }
    ans = max(ans, head[G[u]]->query(pos[u], pos[v]));
    return ans;
}
int main() {
    
    ios::sync_with_stdio(false);
    cin >> n >> q;
    for(int i = 0;i < n-1;i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    
    dfs_init(0, 0, 0);
    dfs_HLD(0);
    
    for(int i = 0;i < q;i++) {
        int type;
        cin >> type;
        if(type == 1) {
            int u, x;
            cin >> u >> x;
            head[G[u]]->update(pos[u], x);
        }else {
            int u, v;
            cin >> u >> v;
            cout << query(u, v) << "\n";
        }
    }
    
    return 0;
}









In   Java  :







import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

 
    // array to store values for each node(vertices)
    static int[] v;
    // array to store connections (edges)
    static ArrayList<Integer>[] e;
    
    // some node with single connection will be tree root
    static int root; 
    // direction to reach root for each node
    static int[] dirToRoot;
    // distance to root
    static int[] distToRoot;
    
    // maximum node value 
    static int totalMax = 0;
    
    static void markRoot(){
        for(int i=0; i<v.length; i++){
            if(e[i].size()==1){
                root = i;
                break;
            }
        }
    }
    
 static void markPathToRoot(int node, int dist, boolean[] visited){
        distToRoot[node] = dist;
        for(Integer item : e[node]){
            int index = item.intValue();
            if(visited[index]==false){
                dirToRoot[index] = node;
                visited[index] = true;
                markPathToRoot(index, dist+1, visited);
            }
        }
    }
    
    static int findMax2(int start, int finish){
        int sDistance = distToRoot[start];
        int fDistance = distToRoot[finish];

        int sIndex = start;
        int fIndex = finish;
        int max = Math.max(v[sIndex], v[fIndex]);
        
        // decrease distance from the one that is more far from root
        while(sDistance>fDistance && max<totalMax){
            sIndex = dirToRoot[sIndex];
            max = max >= v[sIndex] ? max : v[sIndex];
            sDistance--;
        }
        while(fDistance>sDistance && max<totalMax){
            fIndex = dirToRoot[fIndex];
            max = max >= v[fIndex] ? max : v[fIndex];
            fDistance--;
        }

        // run both of them
        while(sIndex!=fIndex){
            fIndex = dirToRoot[fIndex];
            sIndex = dirToRoot[sIndex];
            max = max >= v[fIndex] ? max : v[fIndex];
            max = max >= v[sIndex] ? max : v[sIndex];
            if(sIndex==root || max==totalMax)
                break;
        }
        return Math.max(max, v[sIndex]);
    }
    
    // calculate distance to root node from each node
    static void resetRoot(){
        // direction to the root of tree for each node
        dirToRoot = new int[v.length];
        distToRoot= new int[v.length];
        
        // mark node with only one edge as root
        markRoot();
//        System.out.println("root="+root);
        
        dirToRoot[root] = root;
        boolean[] visited = new boolean[v.length];
        visited[root] = true;
        markPathToRoot(root, 0, visited);
    }
    
    public static void main(String[] args) {
        Reader sc = new Reader();
        sc.init(System.in);
        int N = sc.nextInt();
        int Q = sc.nextInt();
        
        // array to store values for each node(vertices)
        v = new int[N];
        // array to store connections (edges)
        e = new ArrayList[N];

        for(int i=0; i<N; i++)
            e[i] = new ArrayList<Integer>(2);
        
        for(int i=0; i<N-1; i++){
            int v1 = sc.nextInt();
            int v2 = sc.nextInt();
            // add to both because undirectional
            e[v1].add(v2);
            e[v2].add(v1);
        }
        
        resetRoot();
        
        // read queries
        while(Q-->0){
            int type = sc.nextInt();
            if(type==1){
                int node    = sc.nextInt();
                int value   = sc.nextInt();
                v[node] = value;
                totalMax = value > totalMax ? value : totalMax;
            }else{
                int start   = sc.nextInt();
                int finish  = sc.nextInt();
                //search for solution
                System.out.println( findMax2(start, finish) );
            }
        }
    }
    
// code from internet    
/** Class for buffered reading int and double values */
static class Reader {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */
    static void init(InputStream input) {
     reader = new BufferedReader( new InputStreamReader(input) );
        tokenizer = new StringTokenizer("");
    }

    /** get next word */
    static String next() {
        while ( ! tokenizer.hasMoreTokens() ) {
            //TODO add check for eof if necessary
            try{
                tokenizer = new StringTokenizer( reader.readLine() );
            }catch(Exception e){}
        }
        return tokenizer.nextToken();
    }

    static int nextInt() {
        return Integer.parseInt( next() );
    }
	
    static double nextDouble() {
        return Double.parseDouble( next() );
    }
}
}








In   Python3  :







def segtree_init(ary):
   ary = list(ary)
   seg = [ary]
   while len(ary) > 1:
      if len(ary) & 1: ary.append(0)
      ary = [max(ary[i],ary[i+1]) for i in range(0,len(ary),2)]
      seg.append(ary)
   return seg
def segtree_set(seg, i, x):
   ary = seg[0]
   ary[i] = x
   for j in range(1, len(seg)):
      x = max(ary[i], ary[i^1])
      ary = seg[j]
      i >>= 1
      ary[i] = x
def segtree_max(seg, lo, hi):
   m = 0
   j = 0
   while lo < hi:
      ary = seg[j]
      if lo & 1:
         x = ary[lo]
         if x > m: m = x
         lo += 1
      if hi & 1:
         hi -= 1
         x = ary[hi]
         if x > m: m = x
      lo >>= 1
      hi >>= 1
      j += 1
   return m
class heavy_light_node:
   def __init__(self, segtree):
      self.parent = None
      self.pos = -1
      self.segtree = segtree
def build_tree(i, edges, location):
   children = []
   members = [i]
   ed = edges[i]
   while ed:
      for j in range(1,len(ed)):
         child = build_tree(ed[j], edges, location)
         child.pos = len(members) - 1
         children.append(child)
      i = ed[0]
      members.append(i)
      ed = edges[i]
   node = heavy_light_node(segtree_init(0 for j in members))
   for child in children:
      child.parent = node
   for j in range(len(members)):
      location[members[j]] = (node, j)
   return node
def read_tree(N):
   edges = [[] for i in range(N)]
   for i in range(N-1):
      x, y = map(int, input().split())
      edges[x].append(y)
      edges[y].append(x)
   size = [0] * N
   active = [0]
   while active:
      i = active[-1]
      if size[i] == 0:
         size[i] = 1
         for j in edges[i]:
            edges[j].remove(i)
            active.append(j)
      else:
         active.pop()
         edges[i].sort(key=lambda j: -size[j])
         size[i] = 1 + sum(size[j] for j in edges[i])
   location = [None] * N
   build_tree(0, edges, location)
   return location
def root_path(i, location):
   loc = location[i]
   path = [ loc ]
   loc = loc[0]
   while loc.parent != None:
      path.append((loc.parent, loc.pos))
      loc = loc.parent
   path.reverse()
   return path
def max_weight(x, y):
   px = root_path(x, location)
   py = root_path(y, location)
   m = 1
   stop = min(len(px), len(py))
   while m < stop and px[m][0] == py[m][0]: m += 1
   loc, a = px[m-1]
   b = py[m-1][1]
   if a > b: a, b = b, a
   w = segtree_max(loc.segtree, a, b+1)
   for j in range(m, len(px)):
      loc, i = px[j]
      x = segtree_max(loc.segtree, 0, i+1)
      if x > w: w = x
   for j in range(m, len(py)):
      loc, i = py[j]
      x = segtree_max(loc.segtree, 0, i+1)
      if x > w: w = x
   return w
N, Q = map(int, input().split())
location = read_tree(N)
for i in range(Q):
   t, x, y = map(int, input().split())
   if t == 1:
      loc, i = location[x]
      segtree_set(loc.segtree, i, y)
   elif t == 2:
      print(max_weight(x, y))
                        








View More Similar Problems

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 →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →