HDU 4857 逃生(拓扑排序)

  • 原题链接: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;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值