您的位置:首页 > 其它

题目1449:确定比赛名次(拓扑排序问题)

2017-04-21 17:45 375 查看
题目链接:http://ac.jobdu.com/problem.php?pid=1449

详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus

参考代码:

//
//  1449 确定比赛名次.cpp
//  Jobdu
//
//  Created by PengFei_Zheng on 21/04/2017.
//  Copyright © 2017 PengFei_Zheng. All rights reserved.
//

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
#include <vector>
#include <queue>
#define MAX_SIZE 501

using namespace std;

int inDegree[MAX_SIZE];
vector<int> edge[MAX_SIZE];
priority_queue< int, vector<int>, greater<int> > myQueue;

int n, m;

int main(){
while(scanf("%d%d",&n,&m)!=EOF){
//initation
for(int i = 1 ; i <= n ; i++){
inDegree[i]=0;
edge[i].clear();
}
while(!myQueue.empty()) myQueue.pop();

while(m--){
int p1, p2;
scanf("%d%d",&p1,&p2);
edge[p1].push_back(p2);
inDegree[p2]++;
}
for(int i = 1 ; i <= n ; i++){
if(inDegree[i] == 0){
myQueue.push(i);
}
}
//there is no need to judge  whether the graph is legal or not.
int ans = 0;
while(!myQueue.empty()){
ans++;
int nowP = myQueue.top();
ans == n ? printf("%d\n",nowP) : printf("%d ",nowP);
myQueue.pop();//remove the node which has the smaller id and inDegree is equal to 0

for(int i = 0 ; i < edge[nowP].size() ; i++){//update the node's inDegree
inDegree[edge[nowP][i]]--;
if(inDegree[edge[nowP][i]]==0){
myQueue.push(edge[nowP][i]);//add new node(inDegree is 0) to the priority_queue
}
}
}
}
return 0;
}
/**************************************************************
Problem: 1449
User: zpfbuaa
Language: C++
Result: Accepted
Time:10 ms
Memory:1532 kb
****************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: