기본 콘텐츠로 건너뛰기

[C++] priority queue 사용법

#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int>> adj;
vector<int> cnt;
int N,M;
void bfs(){
priority_queue<int, vector<int>,greater<int>> q;
for (int i=1;i<=N;i++){
if (cnt[i] == 0)
{
q.push(i);
}
}
while (!q.empty()){
int now = q.top();
printf("%d ",now);
q.pop();
for (int i=0;i<adj[now].size();i++){
int next = adj[now][i];
cnt[next]--;
if (cnt[next] == 0)
{
q.push(next);
}
}
}
}
int main(void){
scanf("%d %d",&N,&M);
adj.resize(N+1);
cnt.resize(N+1);
for (int i=1;i<=N;i++){
cnt[i] = 0;
}
for (int i=0;i<M;i++){
int a,b;
scanf("%d %d",&a,&b);
adj[a].push_back(b);
cnt[b]++;
}
bfs();
}

댓글

이 블로그의 인기 게시물

Tree traversal의 3가지

1. 전위 순회 (Preorder Traversal) Root -> Left Tree -> Right Tree   ( 루트를 제일 처음에 방문 ) 2. 중위 순회 (Inorder Traversal) Left Tree -> Root -> Right Tree   ( 루트를 중간에 방문 ) 3. 후위 순회 (Postorder Traversal) Left Tree -> Right Tree -> Root   ( 루트를 제일 마지막에 방문 ) <소스코드> 출처 : http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder /// C program for different tree traversals #include <stdio.h> #include <stdlib.h> /* A binary tree node has data, pointer to left child    and a pointer to right child */ struct node {      int data;      struct node* left;      struct node* right; }; /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */ struct node* newNode(int data) {      struct node* node = (struct node*)                 ...