FZU题单

Priority Queue

 Aizu - ALDS1_9_C 

使用优先队列,根据输入字符串插入,提取或结束,当提取时使用pop删除队首元素

#include <iostream>
#include <queue>
using namespace std;
int main()
{
	priority_queue<int> q;
	int x;
	string s;
	while (1)
	{
		cin >> s;
		if (s == "insert")
		{
			cin >> x;
			q.push(x);
		}
		else if (s == "extract")
		{
			cout << q.top() << endl;
			q.pop();
		}
		else if (s == "end")
			break;
	}

	return 0;
}

合并果子

 洛谷 - P1090 

优先队列,小根堆,将前两个最小的元素相加

#include <iostream>
#include <queue>
using namespace std;
int main()
{
	int n,x;
	cin >> n;
	priority_queue<int,vector<int>,greater<int>> q;
	while (n--)
	{
		cin >> x;
		q.push(x);
	}
	int s1, s2, s = 0;
	while(q.size() >= 2)
	{
		s1 = q.top();
		q.pop();
		s2 = q.top();
		q.pop();
		s += s1 + s2;
		q.push(s1+s2);
	}
	cout << s;
	return 0;
}

 约瑟夫问题

 洛谷 - P1996 

使用队列,如果符合条件则输出队首元素,然后删除,若不符合,则将队首元素移动至队尾

#include <iostream>
#include <queue>
using namespace std;
int main()
{
	int n,m;
	cin >> n >> m;
	queue<int> q;
	for (int i = 1; i <= n; i++)
	{
		q.push(i);
	}
	int c = 1;
	while (!q.empty())
	{
		if (c == m)
		{
			cout << q.front() << " ";
			q.pop();
			c = 1;
		}
		else
		{
			c++;
			q.push(q.front());
			q.pop();
		}
	}
}

 Look Up S

 洛谷 - P2947 

栈,从右往左数,将当前数据与栈中元素进行比较,小于等于的就删除,然后对栈中是否存在元素进行判断,若存在,则将所存元素计入答案,反之则为0

#include <iostream>
#include <stack>
using namespace std;

const int N = 1e5;
int a[N],ans[N];
stack<int> s;
int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
	}
	for (int i = n; i > 0; i--)
	{
		while (!s.empty() && a[s.top()] <= a[i])
		{
			s.pop();
		}
		if (!s.empty())
		{
			ans[i] = s.top();
		}
		else
			ans[i] = 0;
		s.push(i);
	}
	for (int i = 1; i <= n; i++)
	{
		cout << ans[i] << endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值