結果
| 問題 |
No.1023 Cyclic Tour
|
| コンテスト | |
| ユーザー |
gew1fw
|
| 提出日時 | 2025-06-12 18:51:50 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 949 ms / 2,000 ms |
| コード長 | 3,308 bytes |
| コンパイル時間 | 235 ms |
| コンパイル使用メモリ | 82,044 KB |
| 実行使用メモリ | 280,312 KB |
| 最終ジャッジ日時 | 2025-06-12 18:52:42 |
| 合計ジャッジ時間 | 33,293 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 49 |
ソースコード
import sys
from sys import stdin
from collections import defaultdict
sys.setrecursionlimit(1 << 25)
def main():
input = sys.stdin.read().split()
ptr = 0
N = int(input[ptr])
ptr += 1
M = int(input[ptr])
ptr += 1
roads = []
edges = defaultdict(list)
for i in range(M):
a = int(input[ptr])
ptr += 1
b = int(input[ptr])
ptr += 1
c = int(input[ptr])
ptr += 1
roads.append((a, b, c))
if c == 1:
edges[(a, b)].append(i)
edges[(b, a)].append(i)
else:
edges[(a, b)].append(i)
# Step 1: Check for pairs of edges in opposite directions from different roads
found = False
for i in range(M):
a, b, c = roads[i]
reverse_roads = edges.get((b, a), [])
for r in reverse_roads:
if r != i:
found = True
break
if found:
break
if found:
print("Yes")
return
# Step 2: Build the directed graph for SCC computation
graph = [[] for _ in range(N + 1)]
for a, b, c in roads:
graph[a].append(b)
if c == 1:
graph[b].append(a)
# Compute SCC using Tarjan's algorithm
index = 0
indices = [0] * (N + 1)
low = [0] * (N + 1)
on_stack = [False] * (N + 1)
stack = []
scc = []
def strongconnect(v):
nonlocal index
indices[v] = index
low[v] = index
index += 1
stack.append(v)
on_stack[v] = True
for w in graph[v]:
if indices[w] == 0:
strongconnect(w)
low[v] = min(low[v], low[w])
elif on_stack[w]:
low[v] = min(low[v], indices[w])
if low[v] == indices[v]:
component = []
while True:
w = stack.pop()
on_stack[w] = False
component.append(w)
if w == v:
break
scc.append(component)
for v in range(1, N + 1):
if indices[v] == 0:
strongconnect(v)
node_component = [0] * (N + 1)
for i, component in enumerate(scc):
for node in component:
node_component[node] = i
# Step 3: Check unidirectional roads
for i in range(M):
a, b, c = roads[i]
if c == 2:
if node_component[a] == node_component[b]:
print("Yes")
return
# Step 4: Check for cycles in the undirected graph of bidirectional roads using DSU
parent = list(range(N + 1))
def find(u):
while parent[u] != u:
parent[u] = parent[parent[u]]
u = parent[u]
return u
def union(u, v):
u_root = find(u)
v_root = find(v)
if u_root == v_root:
return False
parent[v_root] = u_root
return True
cycle_found = False
parent = list(range(N + 1))
for i in range(M):
a, b, c = roads[i]
if c == 1:
x = find(a)
y = find(b)
if x == y:
cycle_found = True
break
union(x, y)
if cycle_found:
print("Yes")
return
print("No")
if __name__ == "__main__":
main()
gew1fw