结构体如何用multiset
c++语言中,multiset是<set>库中一个非常有用的类型,它可以看成一个序列,插入一个数,删除一个数都能够在O(logn)的时间内完成,而且他能时刻保证序列中的数是有序的,而且序列中可以存在重复的数。
自定义类型的数据呢?
不只是int类型,multiset还可以存储其他的类型诸如 string类型,结构(struct或class)类型。而我们一般在编程当中遇到的问题经常用到自定义的类型,即struct或class。例如下面的例子:
struct rec{
int x,y;
};
multiset<rec> s;
不过以上的代码是没有任何用处的,因为multiset并不知道如何去比较一个自定义的类型。怎么办呢?我们可以定义multiset里面rec类型变量之间的小于关系的含义(这里以x为第一关键字为例),具体过程如下:
定义一个比较类cmp,cmp内部的operator函数的作用是比较rec类型a和b的大小(以x为第一关键字,y为第二关键字):
struct rec {
int x,y;
bool operator<( const node&b )const {
if ( x==b.x ) return y<b.y;
return x>b.x;
}
};
multiset<rec> s;
常用知识点:
1. 得到最小值 ------ *s.begin() .
2. 得到最大值 ------ *s.rbegin() .
3. 删除某个值 ------ s.erase(s.find(x)) .
4. 删除最大值 ------s.erase(s.find(*s.rbegin())) .
5. 二分查找 ------*s.lower_bound( value ) .
例题1:https://vjudge.net/problem/Kattis-gcpc
题意:n个队伍,m条实时消息( i, p )。表示第 i 个队伍成功AC一道题,增加罚时 p. 输出m行,表示每条实时消息后1号队伍的排名。按照AC题数,罚时,队伍编号,来进行排名。
思路:考虑用multiset来存排行榜并进行维护。全存的话就T4了,所以不能全存,我们手动优化后只存比1号队伍排名靠前的,其他的在结构体里暂时存放。
Sample Input 1 | Sample Output 1 |
---|---|
3 4 2 7 3 5 1 6 1 9 | 2 3 2 1 |
代码:
#include <bits/stdc++.h>
using namespace std;
struct node {
int x,y,id;
bool operator<( const node&b )const {
if ( x==b.x && x==0 ) return id<b.id;
if ( x==b.x ) return y<b.y;
return x>b.x;
}
};
multiset<node> s;
node a[200005];
int n,m;
int main()
{
cin >> n >> m;
for ( int i=1; i<=n; i++ ) {
a[i].x=0; a[i].y=0; a[i].id=i;
s.insert(a[i]);
}
for ( int i=0; i<m; i++ ) {
int u,v;scanf("%d %d",&u,&v);
if ( a[u]<a[1] ) s.erase(s.find(a[u]));
a[u].x = a[u].x+1;
a[u].y += v;
s.insert(a[u]);
while ( s.size()>0 && !(*s.rbegin()<a[1]) ) s.erase(s.find(*s.rbegin()));
printf("%d\n",s.size()+1);
}
return 0;
}