- 原题链接:Here!
- 分析:题目n(1 <= n <= 30000)和m(1 <= m <= 100000),肯定不能用数组来保存二元关系(b,a)了,所以采用vector来存放二元关系,然后用优先队列保存入度为0的点。
- CODE:
#include<cstdio> #include<cstring> #include<vector> #include<queue> using namespace std; //#define test const int maxn = 30000+1; int n,m; int topo[maxn]; int indegree[maxn]; vector<int> G[maxn]; struct cmp{ bool operator()(int &a,int &b){ return a<b; } }; void topo_sort(){ priority_queue< int, vector<int>, cmp > Q; for(int i=1;i<=n;i++) if(!indegree[i]) Q.push(i); while(!Q.empty()){ int u=Q.top(); Q.pop(); topo[ ++topo[0] ]=u; for(int v=0;v<G[u].size();v++){ indegree[ G[u][v] ]--; if(indegree[ G[u][v] ]==0) Q.push( G[u][v] ); } } } int main(){ int t,a,b; #ifdef test freopen("Hdu 4857.txt","r",stdin); #endif scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) G[i].clear(); memset(topo,0,sizeof(topo)); memset(indegree,0,sizeof(indegree)); while(m--){ scanf("%d%d",&a,&b);// a号必须在b号之前二元关系即(b,a) G[b].push_back(a); indegree[a]++; } topo_sort(); for(int i=n;i>0;i--){ printf("%d%c",topo[i],i==1?'\n':' '); } } return 0; }
HDU 4857 逃生(拓扑排序)
最新推荐文章于 2021-09-11 12:33:19 发布