stl set

P2234 [HNOI2002]营业额统计

#include <bits/stdc++.h>
using namespace std;
int n, x, ans;
set<int> s;
set<int>::iterator iter, before;
int main()
{
	scanf("%d", &n);
	scanf("%d", &x);
	s.insert(x);
	ans+=x; 
	for(int i=2; i<=n; ++i){
		scanf("%d", &x);
		//找到第一个大于等于x的位置 
		iter=s.lower_bound(x);
		//x在里面是最小的 
		if(iter==s.begin()){	
			ans+=abs(*iter-x);
		}
		else{
            before=iter;
            before--;
			ans+=min(abs(x-*iter), abs(x-*before));
		}
		s.insert(x);
	}
	printf("%d", ans);
	return 0;
}

或者

#include <bits/stdc++.h>
using namespace std;
int n, x, ans;
set<int> s;
set<int>::iterator iter, before;
int main()
{
	scanf("%d", &n);
	s.insert(1e9);
	s.insert(-1e9);
	for(int i=1; i<=n; ++i){
		scanf("%d", &x);
		if(i==1){	
			ans+=x;
		}
		else{
			iter=s.lower_bound(x); 
			before=iter;
			before--;
			ans+=min(abs(x-*iter), abs(x-*before));
		}
		s.insert(x);
	}
	printf("%d", ans);
	return 0;
}

multiset

P1090 [NOIP2004 提高组] 合并果子 / [USACO06NOV] Fence Repair G

#include<bits/stdc++.h>
using namespace std;
int n, x, ans, cur;
multiset<int> s;
multiset<int>::iterator asd;
int main(){
	scanf("%d", &n);
	//nlogn复杂度 
	for(int i=1; i<=n; ++i){	
		scanf("%d", &x);
		s.insert(x);	//将元素插入到multiset中 
	}
	for(int i=1; i<n; ++i){		//总共n-1次即可 
		//每次选最小的两个合并
		cur=0;	 		//当前两个果子的和 
		//找出multiset中当前最小的值 	O(1)的复杂度 
		cur+=*s.begin();		//将它的值加到cur中 
		s.erase(s.begin());		//将最小的值删掉 				O(logn)的复杂度 
		//找出multiset中当前最小的值 	O(1)的复杂度 
		cur+=*s.begin();
		s.erase(s.begin());		//将最小的值删掉 				O(logn)的复杂度 
		ans+=cur;				//加到答案里 
		s.insert(cur);			//将大果子插入到multiset中 
	}
	printf("%d", ans);
	return 0;
}

P5250 【深基17.例5】木材仓库

#include <bits/stdc++.h>
using namespace std;
int n, opt, len, ans1, ans2;
multiset<int> s;
multiset<int>::iterator asd;
int main()
{
	scanf("%d", &n);
	s.insert(-2000000000);
	s.insert(2000000000);
	while(n--){
		scanf("%d %d", &opt, &len);
		if(opt==1){	//放入 
			if(s.count(len)){
				printf("Already Exist\n");
			}
			else{
				s.insert(len);
			}
		}
		else if(opt==2){
			if(s.size()==2){
				printf("Empty\n");
			} 
			else{
				//找到第一个大于等于len的 
				asd=s.lower_bound(len);
				ans2=*asd;
				asd--;
				ans1=*asd;
				if(abs(ans1-len)<=abs(ans2-len)){
					printf("%d\n", ans1);
					s.erase(ans1);
				}
				else{
					printf("%d\n", ans2);
					s.erase(ans2);
				}
			}
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ypeijasd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值