关于结构体和pair的问题
  • 板块P2073 送花
  • 楼主404_notfound
  • 当前回复4
  • 已保存回复4
  • 发布时间2020/8/4 16:31
  • 上次更新2023/11/6 21:19:18
查看原帖
关于结构体和pair的问题
52577
404_notfound楼主2020/8/4 16:31

RT,使用set水题的时候发现把价值当做first,美丽值当做second,凑成一个pair插入set时不会根据first判重

看题解之后手写了结构体,重载运算符之后就能A掉

大佬求教

使用pair的code

#include<bits/stdc++.h>
using namespace std;
const int inf=0x7fffffff;
typedef long long ll;
set<pair<int,int> > s;
signed main()
{
	int cz;
	while(scanf("%d",&cz)&&cz!=-1)
	{
		if(cz==2)//删除最大值 
		{
			if(!s.empty())
			{
				s.erase(--s.end());
			}
		}else if(cz==3)
		{
			if(!s.empty())//删除最小值 
			{
				s.erase(s.begin());
			}
		}else
		{
			int x,y;
			scanf("%d%d",&y,&x);
			s.insert(make_pair(x,y));
		}
	/*	for(set<pair<int,int> >::iterator it = s.begin();it!=s.end();it++)
		{
			pair<int,int> sit=*it;
			cout<<":"<<sit.first<<" "<<sit.second<<endl;
		}*/
	}
	ll s1=0,s2=0;
	for(set<pair<int,int> >::iterator it = s.begin();it!=s.end();it++)
	{
		pair<int,int> sit=*it;
		s1+=sit.first;
		s2+=sit.second;
	}
	printf("%lld %lld\n",s2,s1);
	return 0;
}

使用结构体的code:

#include<bits/stdc++.h>
using namespace std;
const int inf=0x7fffffff;
typedef long long ll;
struct node{
	ll m,v;
	bool operator <(const node &a)const{
		return v<a.v;
	}
};
set<node > s;
signed main()
{
	int cz;
	while(scanf("%d",&cz))
	{
		if(cz==2)//删除最大值 
		{
			if(!s.empty())
			{
				s.erase(--s.end());
			}
		}else if(cz==3)
		{
			if(!s.empty())//删除最小值 
			{
				s.erase(s.begin());
			}
		}else if(cz==1)
		{
			ll x,y;
			scanf("%lld%lld",&x,&y);//输入的是美丽值,价值 
			node pa=(node){x,y};
			s.insert(pa);
		}else
		{
			ll s1=0,s2=0;
			for(set<node >::iterator it = s.begin();it!=s.end();it++)
			{
				node sit=*it;
				s1+=sit.v;
				s2+=sit.m;
			}
			printf("%lld %lld\n",s2,s1);
			return 0;
		}
	}
}
2020/8/4 16:31
加载中...