跳到正文

个人记录

set基本操作

BJpers2约 2 分钟
原文

这是 2025年9月23日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2018年3月3日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

此题为 P2073 代码

(感谢zhengrunzhe大佬的题解)

1.可以用重载运算符来重载默认的顺序

2.可以用 erase((类型名){成员}); 来删除元素

3.可以用set<类型名>::iterator i=s.begin()~s.end()来遍历set

C++
#include<iostream>
#include<cstdio>
#include<set>
using namespace std;
typedef long long ll;
ll w,c,sumw,sumc;int ord;
struct fe{
	ll w,c;
	bool operator < (const fe x)const{
		if(c==x.c) return 0;
		return c>x.c;
	}
}; 
struct fc{
	ll w,c;
	bool operator < (const fc x)const{
		if(c==x.c) return 0;
		return c<x.c;
	}
};
set<fe>se;set<fc>sc;
int main(){
	while(scanf("%d",&ord) && ord>0){
		if(ord==1){
			scanf("%lld%lld",&w,&c);
			se.insert((fe){w,c});
			sc.insert((fc){w,c});
		}
		if(ord==2){//删贵的 
			ll pw=se.begin()->w,pc=se.begin()->c;
			se.erase(*se.begin());
			sc.erase((fc){pw,pc});
		}
		if(ord==3){//删便宜的 
			ll pw=sc.begin()->w,pc=sc.begin()->c;
			sc.erase(*sc.begin());
			se.erase((fe){pw,pc});
		}
	}
	for(set<fe>::iterator i=se.begin();i!=se.end();i++)
	    sumw+=i->w,sumc+=i->c;
	printf("%lld %lld",sumw,sumc);
	return 0;
}