Self-Driving Bus


Problem Statement :


Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities.

The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true:

There is a path between every pair of cities which belongs to the subset.
Every city in the path must belong to the subset.

Input Format

The first line contains a single positive integer , n. The n - 1 subsequent lines each contain two positive space-separated integers, ai  and bi , describe an edge connecting two nodes in tree T.

Constraints

1  <=  n  <=  2 x 10^5
1  <=  ai , bi  <=  n 

Output Format

Print a single integer: the number of segments [ L , R ], which are connected in tree T.


Solution :



title-img


                            Solution in C :

In  C++  :





#include<iostream>
#include<vector>
using namespace std;

typedef long long int lli;
typedef pair<lli,lli> ii;
typedef vector<lli> vi;
typedef vector<vi> vii;

const lli MAXN = 200200;
lli par[MAXN], upr[MAXN],dnr[MAXN];
lli run_upr[MAXN], run_dnr[MAXN], grand[MAXN];
vii G(MAXN);

void set_parents(lli m,lli a,lli b, lli p){
  upr[m] = max(m,upr[p]);
  dnr[m] = min(m,dnr[p]);
  par[m] = p;
  grand[m] = grand[p]; 
  for(auto it = G[m].begin() ; it != G[m].end(); it++){
    if((*it) < a || (*it) >= b || (*it) == p) continue;
    set_parents(*it, a, b, m);
  }
}

lli middle_case(lli m, lli a, lli b){
  run_upr[m] = run_dnr[m] = m;
  lli aux;
  for(aux = m ; aux < b && grand[aux] == m ; aux++);
  b = aux;
  for(aux = m ; aux >= a && grand[aux] == m ; aux--);
  a = aux + 1;

  for(lli i = m + 1 ; i < b ; i++){
    run_upr[i] = max(run_upr[i-1], upr[i]);
    run_dnr[i] = min(run_dnr[i-1], dnr[i]);
  }

  for(lli i = m - 1 ; i >= a ; i--){
    run_upr[i] = max(run_upr[i+1], upr[i]);
    run_dnr[i] = min(run_dnr[i+1], dnr[i]);
  }
  lli total = 0; // {m}
  // Contamos [i,d] con i <= m/2, d>= m/2
  for(lli d = m, l = m + 1, r = m+ 1, ct = 0; d < b ; d++){
    if(d != run_upr[d]) continue;
    for(; l - 1>= a && d >= run_upr[l- 1] ;l--){
      if(l-1 == run_dnr[l-1]) ct++;
    }
    for(; r - 1> run_dnr[d] && r > l; r--){
      if(r - 1 == run_dnr[r-1]) ct--;
    }
    total += ct;
  }
  return total;
}

lli solve(lli a, lli b){
  if(a == b){
    return 0;
  }
  if(a + 1 == b){
    return 1;
  }
  lli m = (a+b)/2;
  lli x,y,z;
  upr[m] = par[m] = dnr[m] = grand[m] = m;
  set_parents(m,a,b,m);
  x = middle_case(m,a,b);
  y = solve(a,m);
  z = solve(m + 1,b);
  return (x+y+z);
}

int main(){
  lli n, a,b;
  cin >> n;
  for(int i = 1 ; i<n;i++){
    cin >> a >> b;
    a--;
    b--;
    G[a].push_back(b);
    G[b].push_back(a);
  }
  cout << solve(0,n) << endl;
  return 0;
}








In   Java :








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

public class Solution {

    public static void main(String[] args) {
  
        Scanner sc = new Scanner(System.in);        
        int nodeNum = Integer.parseInt(sc.nextLine());
List<List<Integer>> refer = new ArrayList<List<Integer>>();
        for(int i=0; i<nodeNum; i++) {
            refer.add(new ArrayList<Integer>());
        }
        
        while(sc.hasNextLine()) {
            String[] pair = sc.nextLine().split(" ");
            putRefer(refer, pair[0], pair[1]);
        }
        
        int result = 0;
        for(int i=1; i<=nodeNum; i++) {
            boolean[] battleFront = new boolean[nodeNum];
            expandFront(i, battleFront, refer);
            result++;
            int upto = i;
            for(int j=i+1; j<=nodeNum; j++) {
                if(battleFront[j-1]) {
                    expandFront(j, battleFront, refer);
                    if(allInFront(battleFront, upto, j)) {
                        result++;
                        for(int k=upto+1; k<j; k++) {
                             expandFront(k, battleFront, refer);
                        }
                        upto = j;
                    }
                }
            }
        }
        
        System.out.println(result);
    }
    
    public static void putRefer(List<List<Integer>> refer, String s1, String s2) {
        int a = Integer.parseInt(s1);
        int b = Integer.parseInt(s2);
        List<Integer> tmp = refer.get(a-1);
        tmp.add(b);
        tmp = refer.get(b-1);
        tmp.add(a);
    }
    
    public static void expandFront(int i, 
boolean[] battleFront, List<List<Integer>> refer) {
        List<Integer> tmp = refer.get(i-1);
        battleFront[i-1] = true;
        if(tmp == null) {
            return;
        }
        for(Integer thisInt : tmp) {
            battleFront[thisInt-1] = true;
        }
    }
    
    public static boolean allInFront(boolean[] battleFront, int upto, int j) {
        for(int i=upto; i<j-1; i++) {
            if(battleFront[i] == false) {
                return false;
            }
        }
        return true;
    }
    
    public static void printArray(boolean[] battleFront) {
        for(boolean b : battleFront) {
            System.out.print(b + " ");
        }
        System.out.println(" ");
    }
    
    public static void printList(List<List<Integer>> refer) {
        for(List<Integer> l : refer) {
            if(l == null) {
                System.out.println("null ");
            }
            else {
                for(Integer ii : l) {
                    System.out.print(ii + " ");                    
                }
                System.out.println(" ");
            }
        }        
    }
}









In   Python3 :








from heapq import *
n=int(input())
neighbors = {}

for x in range(n):
    neighbors[x] = []
for i in range(n-1):
    a, b = map(int,input().split())
    neighbors[a-1].append(b-1)
    neighbors[b-1].append(a-1)
def search(source):
    ans = 0
    cur_max = 0
    cur_len = 0
    heap = [source]
    vis = [False for i in range(n)]
    while len(heap) > 0:
        x = heappop(heap)
        cur_max = max(cur_max, x)
        cur_len += 1
        vis[x] = True
        if cur_max - source + 1 == cur_len:
            ans += 1
        for y in neighbors[x]:
            if y >= source and vis[y] == False:
                heappush(heap, y)
    return ans
ans = 0
prev = 0
for x in range(n-1, -1, -1):
    neigh = 0
    plus = 0
    for y in neighbors[x]:
        if y > x:
            neigh += 1
        if y == x + 1:
            plus = 1
    if plus == neigh and plus == 1:
        prev += 1
    else:
        prev = search(x)
    ans += prev
print(ans)
                        




View More Similar Problems

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

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 →