優先佇列的使用方法+OJ案例講解
阿新 • • 發佈:2019-01-04
#include<cstdio> #include<iostream> #include<stack> #include<map> #include<cstring> #include<queue> using namespace std ; struct stone{//這是一種自定義設定優先佇列優先順序的方法,過載預設的 < 符號 int p; int d; friend bool operator< (stone a,stone b){ if(a.p==b.p) return a.d>b.d;/*注意這裡的比較,這是寫的資料越小優先順序越高,即先取出數值小的元素其實也可以這麼理解,佇列我們是可以用陣列來儲存的,比較sort函式裡我們寫的cmp ,return a>b時 是按降序來排列的,eg :6 5 4 3 2 1,因為佇列又是滿足先進先出的原則,所以我們首先取出的是1,也就是數值最小的那個*/ return a.p>b.p; } }; int main() { int t; scanf("%d",&t); while(t--){ int n; priority_queue<stone> st; scanf("%d",&n); stone t; for(int i=0;i<n;i++){ scanf("%d %d",&t.p,&t.d); st.push(t); } int cou=0; stone tp; while(!st.empty()){ tp=st.top(); st.pop(); if(++cou&1){ tp.p+=tp.d; st.push(tp); } } printf("%d\n",tp.p); //程式碼其它的地方都還是很好理解的. } return 0 ; }