It is not guaranteed to be the optimal solution for the minimum of the positive each fetch, and the inverse construction edge can get the maximal positive solution at each time.
Code:
#include <iostream> #include <cstdio> #include <cmath> #include <map> #include <queue># include<vector> #include <cstring> #include <algorithm> #define REP (i,a,b) for (int i= (a);i< (b); i+ +) #define REV (I,a,b) for (int i= (a); i>= (b); i--) #define CLR (a,x) memset (a,x,sizeof a) #define INF 0x3f3f3f3ftypedef Long long ll;using namespace std;const int maxn=205;const int Maxm=maxn*maxn;int FIRST[MAXN],NEX[MAXM],V[MAXM],IN[MAXN] , P[maxn],h[maxn];int n,m,ecnt;bool topsort (int n) {priority_queue<int>q; memset (h,0,sizeof h); for (int i=1;i<=n;i++) if (!in[i]) Q.push (i); int cur=0; while (!q.empty ()) {int x=q.top (); Q.pop (); p[x]=n-(cur++); for (int e=first[x];~e;e=nex[e]) {H[v[e]]=max (h[v[e]],h[x]+1); if (--in[v[e]]==0) Q.push (V[e]); }} return cur==n;} void add_ (int a,int b) {v[ecnt]=b; Nex[ecnt]=first[a]; first[a]=ecnt++;} int main () {int t,a,b; scanf ("%d",&T); while (t--) {scanf ("%d%d", &n,&m); The CLR (first,-1); ecnt=0; CLR (in,0); for (int i=0;i<m;i++) {scanf ("%d%d", &a,&b); Add_ (B,a), in[a]++; } int ans=topsort (n); if (!ans) {puts ("-1"); Continue } for (int i=1;i<=n;i++) printf ("%d%c", p[i],i==n? ' \ n ': '); } return 0;}
POJ 3687 Labeling Balls (reverse topology)