Page 1 of 1
Priority Queues
Posted: Mon Apr 29, 2013 4:09 pm
by Spartan
somebody knows how to use the priority queue of the stl, not with the data type int but with some other structure or class. I'm trying but i don't know how to indicate the priority order. I've already try with overloading operators but i'm having some troubles. Could anyone help me?
Re: Priority Queues
Posted: Wed Oct 23, 2013 12:40 pm
by Dariel
Para este caso lo debemos hacer es sobre cargar el operardor < de la estructura, si tienes una estructura con dos campos Edad y Peso, queremos ordenar de menor a mayor por la edad y el peso.
Code: Select all
#include <cstdio>
using namespace std;
struct Estudiante {
int Edad, Peso;
bool operator<(const Estudiante & Est) const {
return ( (Edad<Est.Edad) || (Edad==Est.Edad && Peso<Est.Peso)) ;
}E[100];
int N;
int main() {
scanf("%d", &N);
for(int i=0; i<N; i++)
scanf("%d%d", &E[i].Edad, &E[i].Peso);
sort(E, E+N);
for(int i=0; i<N; i++)
printf("%d %d\n", E[i]. Edad, E[i].Peso);
return 0;
}
Para el caso de la Cola con prioridad, la cola por defecto escoge el menor y con la sobrecarga del operador < que hicimos anteriormente funciona perfectamente, entonces ¿que debemos hacer? pues lo siguiente:
Code: Select all
#include <cstdio>
#include <queue>
using namespace std;
......
priority_queue <Estudiante> PQ;
Estudiante A;
......
int main {
scanf("%d", &N);
for(int i=0; i<N; i++){
scanf("%d%d", &A.Edad, &A.Peso);
PQ.push(A);
}
while(!PQ.Empty()) {
printf("%d %d\n", PQ.top().Edad, PQ.top().Peso);
PQ.pop();
}
return 0;
}
La idea esta por ahí, espero que esto te ayude...
Salu2, Dariel.