牛客竞赛语法入门班数组栈、队列和stl习题

牛客竞赛语法入门班数组栈、队列和stl习题

L 指纹锁

set ,自带排序功能
可重写排序函数 cmp,注意外边写的要写成 o p e r a t o r ( ) operator() operator(),结构体内部的排序写成 o p e r a t o r < operator< operator<
代码中的排序函数这么理解:
假设 k = 3 k=3 k=3,初始为空,插入一个 2 2 2,如果我们再插入一个 3 3 3,输出发现 s e t set set 里边并没有 3 3 3,这时只有与 2 2 2 绝对值大于 3 3 3 的才能插入。
加入这个自定义的 c m p cmp cmp 排序函数, 当插入( i n s e r t ( x ) insert(x) insert(x))一个数 x x x ,如果存在与其中的数差值的绝对值 < = k <=k <=k,则无法插入,同理, f i n d ( x ) find(x) find(x) 也会按照绝对值误差 < = k <=k <=k 来寻找并返回集合中的与其误差 < = k <=k <=k 的数,找不到返回 e n d ( ) end() end()
code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e6 + 9;
const ll mod = 1e9 + 7;
ll n, m, k;
char s[maxn];
struct cmp
{
	bool operator() (const int &v,const int &u)const{
		if(abs(u - v) <= k) return 0;
		return u < v;//从大到小排,这个无所谓,怎么排都行
	}
};
void work()
{
	scanf("%lld %lld", &m, &k);
	set <int, cmp> se;
	while(m--)
	{
		scanf("%s", s);scanf("%lld", &n);
		
		if(strcmp(s, "add") == 0) se.insert(n);
		else if(strcmp(s, "del") == 0)	se.erase(n);
		else 
		{
			if(se.find(n) != se.end()) printf("Yes\n");
			else printf("No\n");
		}
	}
}

int main()
{
	//ios::sync_with_stdio(0);
	//int TT;cin>>TT;while(TT--)
	work();
	return 0;
}

D [NOIP1998]拼数

排序的妙用

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5 + 9;
const ll mod = 1e9 + 7;
ll n, m, pos;
struct node
{
	string s;
	bool operator<(const node&B)const{
		return s + B.s > B.s + s;
	}
}a[maxn];
void work()
{
	cin >> n;
	for(int i = 1; i <= n; ++i) cin >> a[i].s;
	sort(a + 1, a + 1 + n);
	for(int i = 1; i <= n; ++i) cout << a[i].s;
}

int main()
{
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	//int TT;cin>>TT;while(TT--)
	work();
	return 0;
}

题意:给定入栈顺序,输出字典序最大的出栈顺序
思路:
因为出栈是倒着出栈,所以倒着维护一下最大值
我们着遍历,如果当前的元素大于 [ i + 1 , n ] [i+1,n] [i+1,n] 区间内的最大值,它如果这时候不出栈,那么这个位置顶替它的肯定是比它小的数。
最后一定会全部出栈,因为 n + 1 n+1 n+1 位置是 0 0 0
code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e6 + 9;
const ll mod = 1e9 + 7;
ll n, m, k;
int a[maxn], maxm[maxn];
void work()
{
	stack <int> s;
	cin >> n;
	int l = n;
	for(int i = 1; i <= n; ++i) cin >> a[i];
	maxm[n+1] = 0;
	for(int i = n; i >= 1; --i) maxm[i] = max(maxm[i+1], a[i]);
	for(int i = 1; i <= n; ++i)
	{
		s.push(a[i]);
		while(!s.empty() && s.top() > maxm[i+1])
		{
			cout << s.top() << " ";
			s.pop();
		}
	}
}

int main()
{
	ios::sync_with_stdio(0);
	//int TT;cin>>TT;while(TT--)
	work();
	return 0;
}
/*
8
6 3 2 8 1 4 5 7
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值