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 :
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
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 →