結果
| 問題 |
No.1023 Cyclic Tour
|
| コンテスト | |
| ユーザー |
convexineq
|
| 提出日時 | 2020-04-10 22:18:28 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 681 ms / 2,000 ms |
| コード長 | 2,368 bytes |
| コンパイル時間 | 222 ms |
| コンパイル使用メモリ | 81,920 KB |
| 実行使用メモリ | 113,152 KB |
| 最終ジャッジ日時 | 2024-09-15 20:45:54 |
| 合計ジャッジ時間 | 15,378 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 49 |
ソースコード
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read
class UnionFind:
def __init__(self, n):
self.parent = list(range(n)) #親ノード
self.size = [1]*n #グループの要素数
def root(self, x): #root(x): xの根ノードを返す.
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめる
x, y = self.root(x), self.root(y)
if x == y: return False
if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいように
self.size[x] += self.size[y] #xの要素数を更新
self.parent[y] = x #yをxにつなぐ
return True
def issame(self, x, y): #same(x,y): xとyが同じ組ならTrue
return self.root(x) == self.root(y)
def getsize(self,x): #size(x): xのいるグループの要素数を返す
return self.size[self.root(x)]
n,m = [int(i) for i in readline().split()]
e1 = []
UF = UnionFind(n)
for _ in range(m):
a,b,c = [int(i) for i in readline().split()]
a -= 1
b -= 1
if c==1:
if not UF.merge(a,b):
print("Yes")
exit()
else:
e1.append((a,b))
z = 0
d = {}
for i in range(n):
if i == UF.root(i):
d[i] = z
z += 1
l = len(d)
g = [[] for _ in range(l)]
for a,b in e1:
g[d[UF.root(a)]].append(d[UF.root(b)])
def find_cycle(g):
n = len(g)
used = [0]*n #0:not yet 1: visiting 2: visited
for v in range(n): #各点でDFS
if used[v] == 2: continue
#初期化
stack = [v]
hist = [] #履歴
while stack:
v = stack[-1]
if used[v] == 1:
used[v] = 2 #帰りがけの状態に
stack.pop()
hist.pop()
continue
hist.append(v)
used[v] = 1 #行きがけの状態に
for c in g[v]:
if used[c] == 2: continue
elif used[c] == 1: # cを始点とするサイクル発見!
return "Yes"
else:
stack.append(c)
return "No"
print(find_cycle(g))
convexineq