PAT A 1129(set内部排序)

emmm,刷到这一题困惑我好久,建一个结构体想使用sort函数却发现实现不了,于是想使用vector进行实现,但是每次需要删除vector中与当前输入值相同的结点,因为需要更新当前值出现次数,但是需要有结点位置才能删除,而vector没有find()函数,但是看到一个大佬使用vector和sort函数实现了,不过代码没有注释,奈何本人太笨了没看懂。于是想用set实现,但是set不能使用sort函数。。。查阅资料get到一种新技能,set内部排序,怕以后忘记,记录下来。
在这里插入图片描述
在这里插入图片描述

#include <stdio.h>
#include <set>
#include <algorithm>
using namespace std;
const int maxn = 50005;
int times[maxn] = {0};

struct Node{
    int data;
    int times;
    bool operator<(const Node&b)const{//内部排序,set容器内部按此规则进行排序
        if(times==b.times)
            return data<b.data;
        return times>b.times;
    }
};

set<Node> st;
int main()
{
    int n, k,x;
    scanf("%d%d", &n, &k);
    scanf("%d", &x);
    Node node;
    node.times = ++times[x];
    node.data = x;
    st.insert(node);//第一个不输出单独处理
    
    for(int i=1; i<n; i++){
        scanf("%d", &x);
        printf("%d:", x);
        int aaa=0;
        //输出要求的前k个数
        for(set<Node>::iterator it=st.begin(); it!=st.end()&&aaa<k; it++, aaa++){
           printf(" %d", it->data);
        }
        node.times = times[x];
        node.data = x;
        if(st.find(node)!=st.end()){//值已经在set中出现,删除原来结点,更新出现次数,插入st中
            st.erase(st.find(node));
            node.times = ++times[x];
            node.data = x;
            st.insert(node);
        }else{//第一次出现直接插入
            node.times = ++times[x];
            node.data = x;
            st.insert(node);
        }
        
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值