結果

問題 No.3833 Encounter
コンテスト
ユーザー tyuyu_62
提出日時 2026-11-28 00:13:02
言語 PyPy3
(8.0.1 + ACL)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
WA  
実行時間 -
コード長 10,458 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 85 ms
コンパイル使用メモリ 65,180 KB
実行使用メモリ 115,596 KB
最終ジャッジ日時 2026-11-28 00:13:12
合計ジャッジ時間 8,996 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge6_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41 WA * 3
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

# Library: https://github.com/tyuyu-62/cp-library
from math import gcd, lcm, isqrt
from collections import deque, defaultdict
from itertools import permutations, product
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from random import randint, shuffle
from time import perf_counter as pc
def II(): return int(input())
def LI(dec=0): return [int(x) - dec for x in input().split()]
def SI(): return input()
def LS(): return list(input().split())
mod = 998244353
inf = 2002002002002002002

import sys
sys.setrecursionlimit(10 ** 6)
input = lambda: sys.stdin.readline().rstrip()
_buf = []
def print(*args, sep=" "): _buf.append(sep.join(map(str, args)))
def debug(*args):
    if DEBUG:
        sys.stderr.write(" ".join(map(str, args)) + "\n")
        sys.stderr.flush()
DEBUG = True

# Library: https://github.com/tyuyu-62/cp-library
import heapq


INF = 2002002002002002002


def dijkstra(graph, start_vertex: int) -> list[int]:
    """Return a vertex-indexed list of shortest distances in weighted graph from
    start_vertex. The source has distance zero and unreachable vertices have distance
    INF.

    Constraints:
        Every edge weight is nonnegative.
        Every finite shortest distance is less than INF.

    Time:
        O((N + M) log N).

    Space:
        O(N + M).
    """
    graph.build()
    N = graph.N
    start = graph.start
    to = graph.to
    weight = graph.weight
    shift = N.bit_length()
    mask = (1 << shift) - 1
    distance = [INF] * N
    distance[start_vertex] = 0
    heap = [start_vertex]
    push = heapq.heappush
    pop = heapq.heappop
    while heap:
        code = pop(heap)
        current = code >> shift
        v = code & mask
        if current != distance[v]:
            continue
        i = start[v]
        end = start[v + 1]
        while i < end:
            u = to[i]
            next_distance = current + weight[i]
            if next_distance < distance[u]:
                distance[u] = next_distance
                push(heap, (next_distance << shift) | u)
            i += 1
    return distance


def dijkstra_path(graph, start_vertex: int) -> tuple:
    """Return (distance, parent, parent_edge) lists indexed by vertex for shortest paths
    from start_vertex in weighted graph. The source is its own parent with parent-edge
    ID -1; unreachable vertices have distance INF and -1 in the other lists.

    Constraints:
        Every edge weight is nonnegative.
        Every finite shortest distance is less than INF.

    Time:
        O((N + M) log N).

    Space:
        O(N + M).
    """
    graph.build()
    N = graph.N
    start = graph.start
    to = graph.to
    weight = graph.weight
    edge_id = graph.edge_id
    shift = N.bit_length()
    mask = (1 << shift) - 1
    distance = [INF] * N
    parent = [-1] * N
    parent_edge = [-1] * N
    distance[start_vertex] = 0
    parent[start_vertex] = start_vertex
    heap = [start_vertex]
    push = heapq.heappush
    pop = heapq.heappop
    while heap:
        code = pop(heap)
        current = code >> shift
        v = code & mask
        if current != distance[v]:
            continue
        i = start[v]
        end = start[v + 1]
        while i < end:
            u = to[i]
            next_distance = current + weight[i]
            if next_distance < distance[u]:
                distance[u] = next_distance
                parent[u] = v
                parent_edge[u] = edge_id[i]
                push(heap, (next_distance << shift) | u)
            i += 1
    return distance, parent, parent_edge
# Library: https://github.com/tyuyu-62/cp-library
class Graph:
    """Weighted directed and undirected graph in CSR format.

    ``add_edge`` adds an undirected edge and ``add_arc`` adds a
    directed edge. Both return an edge ID assigned in insertion order.
    Call ``build`` before reading the CSR arrays.
    After ``build``, ``graph[u]`` returns a generator of destinations from
    vertex ``u``.

    Args:
        N: Number of vertices.

    Attributes:
        start: CSR offsets of length N + 1.
        to: Destination vertices in CSR order.
        weight: Arc weights in CSR order.
        edge_id: Original edge IDs in CSR order.
        edge_from: First endpoint or source by edge ID.
        edge_to: Second endpoint or destination by edge ID.
        edge_weight: Weight by edge ID.

    Constraints:
        0 <= N < 2^32.
        All edges and arcs are added before build.

    Time:
        O(N + M) construction and build.

    Space:
        O(N + M).
    """

    __slots__ = (
        "N",
        "start",
        "to",
        "weight",
        "edge_id",
        "edge_from",
        "edge_to",
        "edge_weight",
        "_arcs",
        "_arc_edge_id",
        "_built",
    )

    def __init__(self, N: int) -> None:
        """Initialize an empty N-vertex graph.

        Time:
            O(N).
        """
        self.N = N
        self.start = [0] * (N + 1)
        self.to = []
        self.weight = []
        self.edge_id = []
        self.edge_from = []
        self.edge_to = []
        self.edge_weight = []
        self._arcs = []
        self._arc_edge_id = []
        self._built = False

    def add_edge(self, u: int, v: int, weight=1) -> int:
        """Add an undirected weighted edge and return its edge ID.

        Time:
            Amortized O(1).
        """
        edge_id = len(self.edge_from)
        self.edge_from.append(u)
        self.edge_to.append(v)
        self.edge_weight.append(weight)
        arcs = self._arcs
        arc_edge_id = self._arc_edge_id
        arcs.append((u << 32) | v)
        arc_edge_id.append(edge_id)
        arcs.append((v << 32) | u)
        arc_edge_id.append(edge_id)
        start = self.start
        start[u + 1] += 1
        start[v + 1] += 1
        return edge_id

    def add_arc(self, from_: int, to: int, weight=1) -> int:
        """Add a directed weighted edge and return its edge ID.

        Time:
            Amortized O(1).
        """
        edge_id = len(self.edge_from)
        self.edge_from.append(from_)
        self.edge_to.append(to)
        self.edge_weight.append(weight)
        self._arcs.append((from_ << 32) | to)
        self._arc_edge_id.append(edge_id)
        self.start[from_ + 1] += 1
        return edge_id

    def build(self) -> None:
        """Build the CSR representation.

        Calling build again after completion does nothing.

        Time:
            O(N + M).

        Space:
            O(N + M).
        """
        if self._built:
            return
        N = self.N
        start = self.start
        v = 0
        while v < N:
            start[v + 1] += start[v]
            v += 1
        counter = start.copy()
        arc_count = len(self._arcs)
        to = [0] * arc_count
        weight = [0] * arc_count
        edge_id = [0] * arc_count
        arcs = self._arcs
        arc_edge_id = self._arc_edge_id
        edge_weight = self.edge_weight
        i = 0
        while i < arc_count:
            arc = arcs[i]
            v = arc >> 32
            j = counter[v]
            to[j] = arc & 0xFFFFFFFF
            e = arc_edge_id[i]
            weight[j] = edge_weight[e]
            edge_id[j] = e
            counter[v] = j + 1
            i += 1
        self.to = to
        self.weight = weight
        self.edge_id = edge_id
        self._arcs = []
        self._arc_edge_id = []
        self._built = True

    def __getitem__(self, u: int):
        """Return a generator of destinations from vertex ``u``.

        The graph must be built before iterating over the returned generator.

        Time:
            O(1), excluding iteration.

        Space:
            O(1), excluding the returned generator.
        """
        start = self.start
        to = self.to
        i = start[u]
        end = start[u + 1]
        while i < end:
            yield to[i]
            i += 1

    def size(self) -> int:
        """Return the number of vertices.

        Time:
            O(1).
        """
        return self.N

    def edge_count(self) -> int:
        """Return the number of added edges and arcs.

        Time:
            O(1).
        """
        return len(self.edge_from)

    def arc_count(self) -> int:
        """Return the number of directed arcs in CSR.

        An undirected edge contributes two arcs.

        Time:
            O(1).
        """
        if self._built:
            return len(self.to)
        return len(self._arcs)

    def __str__(self) -> str:
        """Return the graph size and edge count.

        Time:
            O(1).
        """
        return (
            f"Graph(N={self.N}, "
            f"edges={len(self.edge_from)}, "
            f"arcs={self.arc_count()})"
        )

def solve():
    N, M = LI()
    G = Graph(N)
    g = [(-1, -1) for _ in range(N)]
    for i in range(M):
        a, b, c = LI(1)
        c += 1
        G.add_edge(a, b, c)
        if g[a][0] == -1 or g[a][1] > c:
            g[a] = (b, c)
        if g[b][0] == -1 or g[b][1] > c:
            g[b] = (a, c)
    L = dijkstra(G, 0)
    R = dijkstra(G, N - 1)
    now = N - 1
    t = 0
    seen = [0] * N
    seen[now] = 1
    S = L[N - 1]
    while True:
        nxt, l = g[now]
        if R[nxt] + L[nxt] == S and L[nxt] == t + l:
            print("Yes")
            return
        if seen[nxt]:
            if L[nxt] + R[now] + l == S or L[now] + R[nxt] + l == S:
                # [t, inf) と [L[now], L[nxt]]の交わりを判定
                if max(t, min(L[nxt], L[now])) <= max(L[nxt], L[now]):
                    print("Yes")
                    return
            # now, nxtでの判定
            if R[nxt] + L[nxt] == S and L[nxt] >= t - l and (L[nxt] - t + l) % (2 * l) == 0:
                print("Yes")
                return
            if R[now] + L[now] == S and L[now] >= t and (L[now] - t) % (2 * l) == 0:
                print("Yes")
                return
            break
        seen[nxt] = 1
        if L[nxt] + R[now] + l == S or L[now] + R[nxt] + l == S:
            # [t, t + l] と [L[now], L[nxt]]の交わりを判定
            if max(t, min(L[nxt], L[now])) <= min(t + l, max(L[nxt], L[now])):
                print("Yes")
                return
        t += l
        now = nxt
    print("No")
    return

if __name__ == "__main__":
    T = 1
    # T = II()
    for _ in range(T):
        solve()
    sys.stdout.write("\n".join(_buf) + "\n")
0