結果
問題 | No.1290 Addition and Subtraction Operation |
ユーザー | vwxyz |
提出日時 | 2023-03-21 21:00:05 |
言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
結果 |
AC
|
実行時間 | 519 ms / 2,000 ms |
コード長 | 3,006 bytes |
コンパイル時間 | 224 ms |
コンパイル使用メモリ | 12,928 KB |
実行使用メモリ | 45,752 KB |
最終ジャッジ日時 | 2024-09-18 14:30:21 |
合計ジャッジ時間 | 21,926 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 85 |
ソースコード
import sys readline=sys.stdin.readline from collections import defaultdict class UnionFind: def __init__(self,N,label=None,f=None,weighted=False): self.N=N self.parents=[None]*self.N self.size=[1]*self.N self.roots={i for i in range(self.N)} self.label=label if self.label!=None: self.label=[x for x in label] self.f=f self.weighted=weighted if self.weighted: self.weight=[0]*self.N def Find(self,x): stack=[] while self.parents[x]!=None: stack.append(x) x=self.parents[x] if self.weighted: w=0 for y in stack[::-1]: self.parents[y]=x w+=self.weight[y] self.weight[y]=w else: for y in stack[::-1]: self.parents[y]=x return x def Union(self,x,y,w=None): root_x=self.Find(x) root_y=self.Find(y) if root_x==root_y: if self.weighted: if self.weight[y]-self.weight[x]==w: return True else: return False else: if self.size[root_x]<self.size[root_y]: x,y=y,x root_x,root_y=root_y,root_x if self.weighted: w=-w self.parents[root_y]=root_x self.size[root_x]+=self.size[root_y] self.roots.remove(root_y) if self.label!=None: self.label[root_x]=self.f(self.label[root_x],self.label[root_y]) if self.weighted: self.weight[root_y]=w+self.weight[x]-self.weight[y] def Size(self,x): return self.size[self.Find(x)] def Same(self,x,y): return self.Find(x)==self.Find(y) def Label(self,x): return self.label[self.Find(x)] def Weight(self,x,y): root_x=self.Find(x) root_y=self.Find(y) if root_x!=root_y: return None return self.weight[y]-self.weight[x] def Roots(self): return list(self.roots) def Linked_Components_Count(self): return len(self.roots) def Linked_Components(self): linked_components=defaultdict(list) for x in range(self.N): linked_components[self.Find(x)].append(x) return linked_components def __str__(self): linked_components=defaultdict(list) for x in range(self.N): linked_components[self.Find(x)].append(x) return "\n".join(f"{r}: {m}" for r,m in linked_components.items()) N,M=map(int,readline().split()) B=[0]+list(map(int,readline().split()))+[0] for i in range(1,N+1,2): B[i]*=-1 diff=[B[i+1]-B[i] for i in range(N+1)] UF=UnionFind(N+1) for m in range(M): l,r=map(int,readline().split()) l-=1 UF.Union(l,r) ans="YES" for r,lst in UF.Linked_Components().items(): if sum(diff[x] for x in lst): ans="NO" print(ans)