第一道逆拓扑纪念一下。。。
#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[20010]; void topsort(){ int l=0; while(1){ int j; int s=0; for(j=1;j<=n;j++){ if(Mark[j]==0){ sum+=num; --Mark[j]; ++s; vis[s]=j; ++l; } } num++; if(l==n) break; if(!s){ flag=1; break; } else{ for(int i=1;i<=s;i++){ for(int k=1;k<=m;k++){ if(cmp[k].y==vis[i]&&Mark[cmp[k].x]!=0&&cmp[k].flag==0){ --Mark[cmp[k].x]; cmp[k].flag=1; } } } } } } int main() { while(scanf("%d %d",&n,&m)!=EOF){ sum=0; num=888; memset(vis,0,sizeof(vis)); memset(Mark,0,sizeof(Mark)); for(int i=1;i<=m;i++){ scanf("%d %d",&cmp[i].x,&cmp[i].y); ++Mark[cmp[i].x]; cmp[i].flag=0; } flag=0; topsort(); if(flag) printf("-1\n"); else printf("%lld\n",sum); }return 0; }