1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<stack> 5 using namespace std; 6 struct node 7 { 8 int u; 9 int v; 10 int next; 11 }edge[10001]; 12 int head[10001]; 13 int num=1; 14 int rudu[1001]; 15 stack<int>s; 16 int money[10001]; 17 int ans=0; 18 int main() 19 { 20 int n,m; 21 scanf("%d%d",&n,&m); 22 for(int i=1;i<=n;i++)money[i]=100; 23 for(int i=1;i<=n;i++)head[i]=-1; 24 for(int i=1;i<=m;i++) 25 { 26 scanf("%d%d",&edge[num].v,&edge[num].u); 27 edge[num].next=head[edge[num].u]; 28 rudu[edge[num].v]++; 29 head[edge[num].u]=num++; 30 } 31 int tot=0; 32 for(int i=1;i<=n;i++) 33 { 34 if(rudu[i]==0) 35 { 36 s.push(i); 37 tot++; 38 } 39 } 40 41 while(s.size()!=0) 42 { 43 int p=s.top(); 44 s.pop(); 45 for(int i=head[p];i!=-1;i=edge[i].next) 46 { 47 if(money[edge[i].v]<money[edge[i].u]+1) 48 money[edge[i].v]=money[edge[i].u]+1; 49 rudu[edge[i].v]--; 50 if(rudu[edge[i].v]==0) 51 { 52 s.push(edge[i].v); 53 tot++; 54 } 55 } 56 } 57 if(tot!=n)printf("-1"); 58 else 59 { 60 for(int i=1;i<=n;i++) 61 ans=ans+money[i]; 62 printf("%d",ans); 63 } 64 return 0; 65 }