第一道逆拓扑纪念一下。。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string.h>
#define maxint 999999999
#define MAXN 10005
#define ll long long
using namespace std; int n,m,k,flag,num;
ll sum;
int Mark[MAXN],st[MAXN],vis[MAXN];
struct node{
int x,y;
int flag;
}cmp[]; void topsort(){
int l=;
while(){
int j;
int s=;
for(j=;j<=n;j++){
if(Mark[j]==){
sum+=num;
--Mark[j];
++s;
vis[s]=j;
++l;
}
}
num++;
if(l==n)
break;
if(!s){
flag=;
break;
}
else{
for(int i=;i<=s;i++){
for(int k=;k<=m;k++){
if(cmp[k].y==vis[i]&&Mark[cmp[k].x]!=&&cmp[k].flag==){
--Mark[cmp[k].x];
cmp[k].flag=;
}
}
}
}
}
} int main()
{ while(scanf("%d %d",&n,&m)!=EOF){
sum=;
num=;
memset(vis,,sizeof(vis));
memset(Mark,,sizeof(Mark));
for(int i=;i<=m;i++){
scanf("%d %d",&cmp[i].x,&cmp[i].y);
++Mark[cmp[i].x];
cmp[i].flag=;
}
flag=;
topsort();
if(flag)
printf("-1\n");
else
printf("%lld\n",sum);
}return ;
}