日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

2021算法竞赛入门班第三节课【堆、栈、队列、并查集】等习题

發布時間:2025/3/20 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 2021算法竞赛入门班第三节课【堆、栈、队列、并查集】等习题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 新建 Microsoft Office Word 文檔【小根堆】
  • 加邊的無向圖【并查集】
  • 好串【棧 / 括號匹配】
  • [NOIP2004]合并果子【小根堆】
  • DongDong認親戚【并查集】

新建 Microsoft Office Word 文檔【小根堆】


https://ac.nowcoder.com/acm/problem/17889
用小根堆來維護一個刪除掉的編號,即現在剩余的編號。在用一個編號存目前最大的編號。
當小根堆內有元素就拿堆里的,沒有的話就向后延申。

#include<bits/stdc++.h> using namespace std; unordered_map<int,int>mp; int n,idx=1; priority_queue<int,vector<int>,greater<int> >heap; int main(void) {cin>>n;for(int i=1;i<=n;i++){string op; cin>>op;if(op=="New") {if(heap.size()) {cout<<heap.top()<<endl;mp[heap.top()]++,heap.pop();}else {cout<<idx<<endl;mp[idx++]=1;}}else {int x; cin>>x;if(mp[x]) {puts("Successful");heap.push(x);}else puts("Failed");mp[x]=0;}}return 0; }

加邊的無向圖【并查集】


https://ac.nowcoder.com/acm/problem/14685
就是連通塊的數量減1。

#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int p[N],n,m; int find(int x) {if(x!=p[x]) p[x]=find(p[x]);return p[x]; } int main(void) {cin>>n>>m;for(int i=1;i<=n;i++) p[i]=i;for(int i=1;i<=m;i++){int a,b; cin>>a>>b;p[find(b)]=find(a);}map<int,int>mp;for(int i=1;i<=n;i++) mp[find(i)]++;cout<<mp.size()-1;return 0; }

好串【棧 / 括號匹配】


https://ac.nowcoder.com/acm/problem/21874
很常見的一種括號匹配模型模型,不過這里的括號是ab而不是()而已。

#include<bits/stdc++.h> using namespace std; stack<char>st; int main(void) {string s; cin>>s;for(int i=0;i<s.size();i++){if(s[i]=='a'|| !st.size()) st.push(s[i]);else{if(st.top()=='a'&&s[i]=='b') st.pop();else st.push(s[i]);}}if(st.size()) cout<<"Bad";else cout<<"Good";return 0; }

[NOIP2004]合并果子【小根堆】


https://ac.nowcoder.com/acm/problem/16663

#include<bits/stdc++.h> using namespace std; priority_queue<int,vector<int>,greater<int>>heap; int n,x; long long int sum; int main(void) {cin>>n;for(int i=0;i<n;i++) cin>>x,heap.push(x);while(heap.size()>1) {auto a=heap.top(); heap.pop();auto b=heap.top(); heap.pop();sum+=a+b;heap.push(a+b);}cout<<sum<<endl;return 0; }

DongDong認親戚【并查集】


https://ac.nowcoder.com/acm/problem/23803

#include<bits/stdc++.h> using namespace std; const int N=1e5+10; unordered_map<string,int>hush; int p[N],idx; int find(int x) {if(x!=p[x]) p[x]=find(p[x]);return p[x]; } int get(string x) {if(!hush.count(x)) hush[x]=idx,p[idx]=idx,idx++; return hush[x]; } int n,m; int main(void) {cin>>n>>m;for(int i=0;i<n;i++){string s; cin>>s;get(s);}while(m--){int op; string s1,s2; cin>>op>>s1>>s2;if(op==1){p[find(get(s2))]=find(get(s1));}else{if(find(get(s1))==find(get(s2))) cout<<1<<endl;else cout<<0<<endl;}}return 0; }

總結

以上是生活随笔為你收集整理的2021算法竞赛入门班第三节课【堆、栈、队列、并查集】等习题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。