結果
| 問題 | No.1660 Matrix Exponentiation | 
| コンテスト | |
| ユーザー |  taiga0629kyopro | 
| 提出日時 | 2021-08-27 22:17:43 | 
| 言語 | PyPy3 (7.3.15) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 237 ms / 2,000 ms | 
| コード長 | 1,259 bytes | 
| コンパイル時間 | 235 ms | 
| コンパイル使用メモリ | 82,508 KB | 
| 実行使用メモリ | 104,992 KB | 
| 最終ジャッジ日時 | 2024-11-21 03:03:30 | 
| 合計ジャッジ時間 | 4,233 ms | 
| ジャッジサーバーID (参考情報) | judge5 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 27 | 
ソースコード
from _collections import defaultdict
n,k=map(int,input().split())
root=[[] for i in range(n+10)]
class topological_sort():
    #1-indexed
    #0-indexedはバグる
    def __init__(self,n):
        self.n=n
        self.root=[[] for _ in range(self.n+1)]
        self.deg=[0]*(self.n+1)
    def add(self,a,b):
        #有向辺 a->b の追加
        self.root[a].append(b)
        self.deg[b]+=1
    def const(self):
        #トポロジカルソートした結果を返す
        #不可能なら [] を返す
        deg2=self.deg[:]
        search=[]
        res=[]
        for i in range(1,self.n+1):
            if deg2[i]==0:search.append(i)
        while search:
            now=search.pop()
            res.append(now)
            for next in self.root[now]:
                deg2[next]-=1
                if deg2[next]==0:
                    search.append(next)
        if len(res)==self.n:
            return res
        return []
tp=topological_sort(n)
for i in range(k):
    a,b=map(int,input().split())
    root[a].append(b)
    tp.add(a,b)
tps=tp.const()
if len(tps)==0:
    print(-1)
    exit()
ans=0
dp=[0]*(n+1)
tps.reverse()
for x in tps:
    for y in root[x]:
        dp[x]=max(dp[x],dp[y]+1)
    ans=max(ans,dp[x])
print(ans+1)
            
            
            
        