Pathwalks (Codeforces 960F)
Tags: DP, graphs

You are given a directed graph with n nodes and m edges, with all edges having a certain weight. There might be multiple edges and self loops, and the graph can also be disconnected. You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. Among all such paths, you need to find the the path that has the maximum possible number of edges, and report this value.Please note that the edges picked don't have to be consecutive in the input.

Input: The first line contains two integers n and m (1 ≤ n ≤ 100000,1 ≤ m ≤ 100000) — the number of vertices and edges in the graph, respectively. m lines follows. The i-th of these lines contains three space separated integers ai, bi and wi (1 ≤ ai, bi ≤ n, 0 ≤ wi ≤ 100000), denoting an edge from vertex ai to vertex bi having weight wi

Output: Print one integer in a single line — the maximum number of edges in the path.

Note: The answer for the first sample input is 2: . Note that you cannot traverse  because edge  appears earlier in the input than the other two edges and hence cannot be picked/traversed after either of the other two edges.In the second sample, it's optimal to pick 1-st, 3-rd and 5-th edges to get the optimal answer: . 

Sample Inputs:
3 3
3 1 3
1 2 1
2 3 2

5 5
1 3 2
3 2 3
3 4 5
5 4 0
4 5 8

Sample Outputs:
2

3

Solution (Python):
import bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f(u, v):
    return u * z + v

def update(i, x):
    i += l1
    tree[i] = x
    i //= 2
    while i:
        tree[i] = max(tree[2 * i], tree[2 * i + 1])
        i //= 2
    return

def get_max(s, t):
    (s, t) = (s + l1, t + l1)
    ans = 0
    while s <= t:
        if s % 2 == 0:
            s //= 2
        else:
            ans = max(ans, tree[s])
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            ans = max(ans, tree[t])
            t = (t - 1) // 2
    return ans
(n, m) = map(int, input().split())
abw = [tuple(map(int, input().split())) for _ in range(m)]
z = pow(10, 5) + 5
s = []
for (a, b, w) in abw:
    s.append(f(b, w))
s = list(set(sorted(s)))
s.sort()
l = len(s)
d = dict()
for i in range(l):
    d[s[i]] = i
l1 = pow(2, (l + 1).bit_length())
l2 = 2 * l1
tree = [0] * l2
for (a, b, w) in abw:
    l0 = bisect.bisect_left(s, f(a, 0))
    r0 = bisect.bisect_left(s, f(a, w)) - 1
    update(d[f(b, w)], max(get_max(l0, r0) + 1, tree[d[f(b, w)] + l1]))
ans = tree[1]
print(ans)

Solution (Python):
import bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f(u, v):
    return u * z + v

def update(i, x):
    i += l1
    tree[i] = x
    i //= 2
    while i:
        tree[i] = max(tree[2 * i], tree[2 * i + 1])
        i //= 2
    return

def get_max(s, t):
    (s, t) = (s + l1, t + l1)
    ans = 0
    while s <= t:
        if s % 2 == 0:
            s //= 2
        else:
            ans = max(ans, tree[s])
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            ans = max(ans, tree[t])
            t = (t - 1) // 2
    return ans
(n, m) = map(int, input().split())
abw = [tuple(map(int, input().split())) for _ in range(m)]
z = pow(10, 5) + 5
s = []
for (a, b, w) in abw:
    s.append(f(b, w))
s = list(set(sorted(s)))
s.sort()
l = len(s)
d = dict()
for i in range(l):
    d[s[i]] = i
l1 = pow(2, (l + 1).bit_length())
l2 = 2 * l1
tree = [0] * l2
for (a, b, w) in abw:
    l0 = bisect.bisect_left(s, f(a, 0))
    r0 = bisect.bisect_left(s, f(a, w)) - 1
    update(d[f(b, w)], max(get_max(l0, r0) + 1, tree[d[f(b, w)] + l1]))
ans = tree[1]
print(ans)

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        inf = float('inf')

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import math
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

class SegTree:

    def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None:
        self._op = op
        self._e = e
        if isinstance(v, int):
            v = [e] * v
        self._n = len(v)
        self._log = (self._n - 1).bit_length()
        self._size = 1 << self._log
        self._d = [e] * (2 * self._size)
        for i in range(self._n):
            self._d[self._size + i] = v[i]
        for i in range(self._size - 1, 0, -1):
            self._update(i)

    def set(self, p: int, x: typing.Any) -> None:
        assert 0 <= p < self._n
        p += self._size
        self._d[p] = x
        for i in range(1, self._log + 1):
            self._update(p >> i)

    def get(self, p: int) -> typing.Any:
        assert 0 <= p < self._n
        return self._d[p + self._size]

    def prod(self, left: int, right: int) -> typing.Any:
        assert 0 <= left <= right <= self._n
        sml = self._e
        smr = self._e
        left += self._size
        right += self._size
        while left < right:
            if left & 1:
                sml = self._op(sml, self._d[left])
                left += 1
            if right & 1:
                right -= 1
                smr = self._op(self._d[right], smr)
            left >>= 1
            right >>= 1
        return self._op(sml, smr)

    def all_prod(self) -> typing.Any:
        return self._d[1]

    def max_right(self, left: int, f: typing.Callable[[typing.Any], bool]) -> int:
        assert 0 <= left <= self._n
        assert f(self._e)
        if left == self._n:
            return self._n
        left += self._size
        sm = self._e
        first = True
        while first or left & -left != left:
            first = False
            while left % 2 == 0:
                left >>= 1
            if not f(self._op(sm, self._d[left])):
                while left < self._size:
                    left *= 2
                    if f(self._op(sm, self._d[left])):
                        sm = self._op(sm, self._d[left])
                        left += 1
                return left - self._size
            sm = self._op(sm, self._d[left])
            left += 1
        return self._n

    def min_left(self, right: int, f: typing.Callable[[typing.Any], bool]) -> int:
        assert 0 <= right <= self._n
        assert f(self._e)
        if right == 0:
            return 0
        right += self._size
        sm = self._e
        first = True
        while first or right & -right != right:
            first = False
            right -= 1
            while right > 1 and right % 2:
                right >>= 1
            if not f(self._op(self._d[right], sm)):
                while right < self._size:
                    right = 2 * right + 1
                    if f(self._op(self._d[right], sm)):
                        sm = self._op(self._d[right], sm)
                        right -= 1
                return right + 1 - self._size
            sm = self._op(self._d[right], sm)
        return 0

    def _update(self, k: int) -> None:
        self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1])

def main():
    (n, m) = MII()
    edges = []
    for _ in range(m):
        (u, v, w) = GMI()
        w += 1
        edges.append((u, v, w))
    msk = 10 ** 6
    tmp = [v * msk + w for (u, v, w) in edges]
    tmp = sorted(set(sorted(tmp)))
    seg = SegTree(max, 0, len(tmp))
    for (u, v, w) in edges:
        l = bisect.bisect_left(tmp, u * msk)
        r = bisect.bisect_left(tmp, u * msk + w) - 1
        p = bisect.bisect_left(tmp, v * msk + w)
        seg.set(p, max(seg.get(p), seg.prod(l, r + 1) + 1))
    print(seg.all_prod())
    return
t = 1
for _ in range(t):
    main()