1. 程式人生 > 其它 >遠端連線到輕量應用伺服器PG資料庫

遠端連線到輕量應用伺服器PG資料庫

題目連結 https://www.luogu.com.cn/problem/P1090

這題前幾天一看到這個資料範圍就把我重複排序的想法pass了。。。。

剛巧下午學了堆和哈夫曼樹,所以想到這題不就是用小根堆解嘛?直接模板了。

然後看到標籤裡優先佇列這四個認識又不認識的大字....當時學校在上資料結構的時候只記得有迴圈佇列,沒有提到過優先佇列啊。

(吆西,我最喜歡學新東西了)

最後,一道沒有思路的題變成了一道不想寫的題變成了一道水題(?)


 

優先佇列 AC程式碼:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,x,ans;
4 priority_queue<int,vector<int>,greater<int>>q; 5 int main() 6 { 7 cin>>n; 8 for(int i=1;i<=n;i++) 9 { 10 cin>>x; 11 q.push(x); 12 } 13 while(q.size()>=2) 14 { 15 int a=q.top(); q.pop(); 16 int b=q.top(); q.pop();
17 ans+=a+b; 18 q.push(a+b); 19 } 20 cout<<ans; 21 return 0; 22 }

 

dalao手寫的堆:(其實也是就是堆的模板了)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=10000+10;
 4 int n,heap[maxn],size=0;
 5 void up(int p) //二叉小根堆向上調整(子節點小於父節點就調整)
 6 {
 7     while(p>1)
8 { 9 if(heap[p]<heap[p/2]) 10 { 11 swap(heap[p],heap[p/2]); 12 p/=2; 13 } 14 else break; 15 } 16 } 17 void insert(int val) //二叉堆插入,新元素放在堆底,向上調整 18 { 19 heap[++size]=val; 20 up(size); 21 } 22 void down(int p) //二叉小根堆向下調整 23 { 24 int s=p*2; 25 while(s<=size) 26 { 27 //下面這句話是從左右兒子中選一個更小的做交換 28 if(s<size&&heap[s+1]<heap[s]) s++; 29 if(heap[s]<heap[p]) 30 { 31 swap(heap[s],heap[p]); 32 p=s; 33 s=p*2; 34 } 35 else break; 36 } 37 } 38 void extract() //二叉堆刪除堆頂 39 { 40 heap[1]=heap[size--]; //將堆底移至堆頂,向下調整 41 down(1); 42 } 43 int gettop() //返回堆頂的值 44 { 45 return heap[1]; 46 } 47 int main() 48 { 49 cin>>n; 50 for(int i=1; i<=n; i++) 51 { 52 int a; 53 cin>>a; 54 insert(a); //建立二叉堆 55 } 56 long long ans=0; //其實這裡不會越界,但好像原題資料是3萬 57 while(size>=2) //如果還可合併 58 { 59 int top1=gettop(); //取出堆頂(堆中最小值)後刪除堆頂 60 extract(); 61 int top2=gettop(); //同上 62 extract(); 63 ans+=(top1+top2); 64 insert(top1+top2); //將兩數之和加入二叉堆,重複運算 65 } 66 cout<<ans<<endl; //輸出答案 67 return 0;