首页 > 代码库 > BestCoder Round #1

BestCoder Round #1

逃生

反向拓扑+优先队列+逆序输出

注意一个样例

input:13 13 1answer:3 1 2而不是2 3 1
#include<iostream>#include<cstdio>#include<cstring>#include<vector>#include<queue>#include<algorithm>#define MAXN  30005using namespace std;vector<int> g[MAXN];int in[MAXN];int n;void clear(){    for(int i=1; i<=n; ++i)    {        g[i].clear();        in[i]=0;    }}int main(){    int T;    scanf("%d",&T);    while(T--)    {        int m;        scanf("%d%d",&n,&m);        clear();        while(m--)        {            int a,b;            scanf("%d%d",&a,&b);            g[b].push_back(a);            in[a]++;        }        priority_queue<int,vector<int>,less<int> > pq;        for(int i=1; i<=n; ++i)            if(in[i]==0)                pq.push(i);        vector<int> ans;        while(!pq.empty())        {            int p=pq.top();            pq.pop();            ans.push_back(p);            for(int i=0; i<g[p].size(); ++i)            {                int &u=g[p][i];                in[u]--;                if(!in[u]) pq.push(u);            }        }        for(int i=ans.size()-1; i>=0; --i)            if(i==ans.size()-1) printf("%d",ans[i]);            else printf(" %d",ans[i]);        printf("\n");    }    return 0;}
View Code