1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include<bits/stdc++.h> using namespace std; #define P pair<int,int> const int maxn=1e5; int n,m,K; vector<int> E[maxn+5]; int dg[maxn+5]; int ans[maxn+5],anst; P ae[maxn+5];int aet; bool flg[maxn+5]; priority_queue<int,vector<int>,greater<int>> q; priority_queue<int,vector<int>,less<int>> p; inline void Insert(int u){K--,flg[u]=1,p.push(u);} inline void Delete(int u){ ans[++anst]=u; if(flg[u]) ae[++aet]=P(ans[anst-1],ans[anst]); for(int v:E[u]) if(!(--dg[v])) q.push(v); } signed main(){ int u,v; scanf("%d%d%d",&n,&m,&K); for(int i=1;i<=m;i++){ scanf("%d%d",&u,&v); E[u].emplace_back(v); dg[v]++; } for(int i=1;i<=n;i++) if(!dg[i]) q.push(i); while(q.size()||p.size()){ if(q.size()==0) u=p.top(),p.pop(),Delete(u); else if(q.size()==1){ if(K&&p.size()&&q.top()<p.top()){ u=q.top(),q.pop(),Insert(u); u=p.top(),p.pop(),Delete(u); } else u=q.top(),q.pop(),Delete(u); } else{ if(K) u=q.top(),q.pop(),Insert(u); else u=q.top(),q.pop(),Delete(u); } } for(int i=1;i<=anst;i++) printf("%d ",ans[i]); putchar('\n'); printf("%d\n",aet); for(int i=1;i<=aet;i++) printf("%d %d\n",ae[i].first,ae[i].second); return 0; }
|