Ticket to Ride

Problem Statement :

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game.

There are n cities on the map and n - 1 road plans. Each road plan consists of the following:

Two cities which can be directly connected by a road.
The length of the proposed road.
The entire road plan is designed in such a way that if one builds all the roads, it will be possible to travel between any pair of cities.

A ticket enables you to travel between two different cities. There are m tickets, and each ticket has a cost associated with it. A ticket is considered to be useful if there is a path between those cities.

Simon wants to choose two cities, u and v, and build a minimal number of roads so that they form a simple path between them. Let St  be the sum of costs of all useful tickets and Sr  be the sum of lengths of all the roads Simon builds. The profit for pair ( u, v )  is defined as St - Sr. Note that u and v are not necessarily unique and may be the same cities.

Given n road plans and m ticket prices, help Simon by printing the value of his maximum possible profit on a new line.

Input Format

The first line contains single positive integer, n , denoting the number of cities.
Each of the n - 1  subsequent lines contains three space-separated integers describing the respective values of u , v, and  l for a road plan, where , 1 <= u ,v <= l and u =/ v . Here, u and v are two cities that the road plan proposes to connect and l  is the length of the proposed road.
The next line contains a single positive integer, m, denoting the number of tickets.
Each of the m subsequent lines contains three space-separated integers describing the respective values of u, v, and c for a ticket from city u  to city v (where c is the cost of the ticket).


1  <=  n  <=  2 x 10^5
1  <=  m  <=  10^5
1  <=  l , c  <=  10^9

Output Format

Print a single integer denoting the the maximum profit Simon can make.

Solution :


                            Solution in C :

In   C++  :

#include <bits/stdc++.h>

using namespace std;

#define sz(x) ((int) (x).size())
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define forab(i,a,b)for(int i =int(a);i<int(b);++i)

typedef long long ll;
typedef long double ld;

const int INF = 1000001000;
const ll INFL = 2000000000000001000;
int solve();

int main()
#ifdef LOCAL
assert(freopen("test.in", "r", stdin));
int tn = 1;
for (int i = 0; i < tn; ++i)
#ifdef LOCAL
cerr << "Time: " << double(clock()) / 

const int maxn = 500001;
const int maxm = 100001;
const int maxh = 19;

int ROOT;

int n;
vector<pair<int, int>> g[maxn];
int in[maxn], out[maxn];
int timer = 0;

const int base = 1 << maxh;
ll t[base * 2];
ll upd[base * 2];

ll get()
return t[1] + upd[1];

int l, r, delta;
inline void put(int v = 1, 
int cl = 0, int cr = base)
if (r <= cl || cr <= l)
if (l <= cl && cr <= r)
upd[v] += delta;
int cc = (cl + cr) >> 1;
put(v << 1, cl, cc);
put((v << 1) + 1, cc, cr);
t[v] = max(t[v << 1] + upd[v << 1], 
t[(v << 1) + 1] + upd[(v << 1) + 1]);

inline void add(int v, ll delta)
l = in[v], r = out[v], ::delta = delta;

vector<pair<int, int>> up[maxn];
vector<pair<int, int>> down[maxn];
vector<pair<int, int>> other[maxn];

inline bool is_prev(int u, int v)
return in[u] <= in[v] && out[v] <= out[u];

ll best = 0;

void go(int u, int prev = ROOT)
for (auto p: other[u])
add(p.first, p.second);
for (auto p: down[u])
add(p.first, -p.second);
upd[1] += p.second;
for (auto p: up[u])
add(p.first, -p.second);
best = max(best, get());
for (auto p: g[u])
if (p.first == prev)
add(p.first, 2 * p.second);
upd[1] -= p.second;
go(p.first, u);
add(p.first, -2 * p.second);
upd[1] += p.second;
for (auto p: other[u])
add(p.first, -p.second);
for (auto p: down[u])
add(p.first, p.second);
upd[1] -= p.second;
for (auto p: up[u])
add(p.first, p.second);

pair<int, int> tickets[maxm];
int ticket_cost[maxm];
int visits[maxm];
int needh[maxm];
int step[maxm];
vector<int> endings[maxn];

int st[maxn], sc = 0;

void dfs(int u, int prev = ROOT, ll depth = 0)
st[sc++] = u;
for (int id: endings[u])
if (visits[id] == 1)
needh[id] = sc;
else if (visits[id] == 2)
step[id] = st[needh[id]];
in[u] = timer++;
t[in[u] + base] = -depth;

for (auto p: g[u])
if (p.first != prev)
dfs(p.first, u, depth + p.second);

for (int id: endings[u])
out[u] = timer;

int solve()
scanf("%d", &n);
ROOT = rand() % n;
forn (i, n - 1)
int u, v, l;
scanf("%d %d %d", &u, &v, &l);
--u, --v;
g[u].emplace_back(v, l);
g[v].emplace_back(u, l);
int m;
scanf("%d", &m);
forn (i, m)
int u, v, c;
scanf("%d %d %d", &u, &v, &c);
--u, --v;
tickets[i] = {u, v};
ticket_cost[i] = c;
fill(step, step + m, -1);
for (int i = base - 1; i > 0; --i)
t[i] = max(t[i * 2], t[i * 2 + 1]);
forn (i, m)
int u = tickets[i].first;
int v = tickets[i].second;
int c = ticket_cost[i];
if (is_prev(v, u))
swap(u, v);
if (is_prev(u, v))
assert(step[i] >= 0);
assert(is_prev(u, step[i]));
assert(is_prev(step[i], v));
u = step[i];
add(v, c);
up[u].emplace_back(v, c);
down[v].emplace_back(u, c);
other[u].emplace_back(v, c);
other[v].emplace_back(u, c);
cout << best << '\n';
return 0;

In   Python3  :


import os
import sys
from queue import Queue
class Graph:
    def __init__(self, n, roads):
        self.n = n
        self.tree = dict()
        for i in range(n):
            self.tree[i+1] = []
        for i in range(len(roads)):
            self.tree[roads[i][0]].append((roads[i][1], roads[i][2]))
            self.tree[roads[i][1]].append((roads[i][0], roads[i][2]))

    def find_path(self, a, b, visited):
        if visited is None:
            visited = set()
        if a==b:
            return set([a]), 0
        for c, d in self.tree[a]:
            if c not in visited:
                path, p_length = self.find_path(c, b, visited)
                if path is not None:
                    ext_path = path.copy()
                    return ext_path, p_length + d
        return None, 0

# Complete the solve function below.
def solve(roads, tickets):
    max_score = 0
    n = len(roads)+1
    g = Graph(n, roads)
    for a, b, _ in tickets:
        path, cost = g.find_path(a, b, None)
        score = - cost
        for t in tickets:
            if set(t[:2]).issubset(path):
                score += t[2]
        if score > max_score:
            max_score = score
    return max_score
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    roads = []

    for _ in range(n-1):
        roads.append(list(map(int, input().rstrip().split())))

    m = int(input())

    tickets = []

    for _ in range(m):
        tickets.append(list(map(int, input().rstrip().split())))

    result = solve(roads, tickets)

    fptr.write(str(result) + '\n')


View More Similar Problems

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

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 →