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

新建 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;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/121858986