HDU1285 determines the ranking of the competition (topological sorting + priority queue)

topic link

http://acm.hdu.edu.cn/showproblem.php?pid=1285

ideas

The result of each game can be regarded as a directed graph, from the winning side to the losing side. The point where the in-degree of this directed graph is 0 is the outermost point where the ranking cannot be determined, and then we follow the numbers from small to small. To the big sorting, save these points in ans, and then we clear all the out degrees of these points, and then look at the next layer, this is actually topological sorting, but we need to ensure that the ranking is not unique. The team with the smaller number, then we can use the priority queue to maintain this topological ordering. For more details, please see the code.

code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f

const int N = 5e2+10;

int n,m;
int du[N];

vector<int> E[N];

void topsort(){
    
    
	vector<int> ans;
	priority_queue<int,vector<int>,greater<int> > que;
	for(int i = 1;i <= n; ++i) 
		if(!du[i]) que.push(i);
	
	while(!que.empty()){
    
    
		int t = que.top();
		que.pop();
		ans.push_back(t);
		for(int i = 0,l = E[t].size();i < l; ++i) {
    
    
			int v = E[t][i];
			du[v]--;
			if(!du[v]) que.push(v);
		}
	}
	for(int i = 0;i < n; ++i)
		cout<<ans[i]<<" \n"[i == n-1];
}


int main()
{
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	while(cin>>n>>m){
    
    
		for(int i = 0;i <= n; ++i) 
			E[i].clear(),du[i] = 0;
		int u,v;
		for(int i = 1;i <= m; ++i) {
    
    
			cin>>u>>v;
			du[v]++;
			E[u].push_back(v);
		}
		topsort();
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_46201544/article/details/123826423