4 add 2 3 find 1 2 remove 2 3 find 1 2 0
Case 1: 2 3 -1
用set 可以很好的解决这道题,set中的元素输入的时候就自动从小到大排序,这里的元素是pair类型,如果pair中的第一个数相同,则按第二个数排序,这和题目要求就相符了。还用了lower_bound 和upper_bound这个函数。一开始犯了个错误,在find查询的时候也把当前输入的一对数插入到了set容器中,不能这样,因为find操作只是单单查询,如果插入了会对后面的操作产生干扰,错误。
lower_bound(val): 返回容器中第一个值【大于或等于】val的元素的iterator位置。 upper_bound(val): 返回容器中第一个值【大于】val的元素的iterator位置。代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <string>
using namespace std;
int main()
{
pair<int,int>p;
int n;char str[10];
int c=1;
while(cin>>n&&n)
{
cout<<"Case "<<c++<<":"<<endl;
set< pair<int,int> >s;
while(n--)
{
scanf("%s",str);
scanf("%d%d",&p.first,&p.second);
if(str[0]==‘a‘)
s.insert(p);
else if(str[0]==‘r‘)
s.erase(p);
else if(str[0]==‘f‘)
{
set< pair<int,int> >::iterator it;
it=s.lower_bound(p);//找到set中第一个比p大的元素的位置,找不到则为s.end()
for(;it!=s.end();it++)
{
if(it->first>p.first&&it->second>p.second)//都大于才符合题意
{
cout<<it->first<<" "<<it->second<<endl;
break;
}
}
if(it==s.end())//找不到
cout<<-1<<endl;
}
}
cout<<endl;
}
return 0;
}
[2010山东ACM省赛] Ivan comes again!(set 的使用),布布扣,bubuko.com
[2010山东ACM省赛] Ivan comes again!(set 的使用)
原文:http://blog.csdn.net/sr_19930829/article/details/23873987