题目要求要求在满足约束条件的情况下,使小的序号尽力靠前。
坑点就在这里,小的序号尽量靠前并不是代表字典序,它要求多种情况时,先使1靠前(可能1只能在第2或第3位 那么就要使它在第2位),其次2,3。。而不是在当前情况下,该位最小是哪个就输出哪个
所以直接拓扑排序,或者优先队列都是错的,因为这样都只能保证字典序最小。可以参考代码后面的样例理解
正确做法应该是 反向建图后,用最大值优先的优先队列来拓扑排序,这样能保证在可能的情况下,先选最大的,把最小的留到最后选。
#include
#include
#include
#include
#include
#include
#include
const int maxn=30010; using namespace std; vector
e[maxn]; int n,m,in[maxn],ans[maxn],cnt; struct cmp { bool operator ()(int &a,int &b){ return a
,cmp> q; for(int i=1;i<=n;i++) if(in[i]==0) q.push(i); int flag=0; int x,i; while(!q.empty()) { x=q.top(); q.pop(); ans[++cnt]=x; for(i=0;i
0;i--) printf(" %d",ans[i]); puts(""); } return 0; } /* 4 2 3 2 4 1 应该输出4132 ?*/