The face is here!
To have a unique topological order, the queue must always have only one element when the topology is ordered, and a check on the two points is fine.
#include <bits/stdc++.h> #define LL long longusing namespace Std;const int N=1e5+5;int hd[n],to[n],ne[n],num,n,m; int d[n],ans=-1,mid;inline void Add (int x,int y) {to[++num]=y,ne[num]=hd[x],hd[x]=num;} inline bool Check () {memset (d,0,sizeof (d)); int x=0,y;for (int i=1;i<=mid;i++) d[to[i]]++;for (int i=1;i<=n;i++) if (!d[i]) if (!x) x=i; else return 0;for (; x;) {y=x,x=0;for (int i=hd[y];i;i=ne[i]) if (i<=mid&&! ( --d[to[i]]) if (!x) x=to[i]; else return 0;} return 1;} int main () {scanf ("%d%d", &n,&m), for (int i=1,uu,vv;i<=m;i++) scanf ("%d%d", &UU,&VV), add (UU,VV); int L=1,r=m;while (l<=r) {mid=l+r>>1;if (check ()) Ans=mid,r=mid-1;else l=mid+1;} printf ("%d\n", ans); return 0;}
codeforces-645d Robot rapping Results report