题解 | 复数集合

#include <math.h>
#include <iostream>
#include <string>
#include <set>

using std::cout;
using std::cin;
using std::endl;
using std::set;
using std::string;

struct Complex{
    Complex(int real, int img)
        :_real(real)
         ,_img(img){}

    int _real;
    int _img;
};

struct ComplexCmp{
    bool operator()(const Complex& c1, const Complex& c2) const{
        if(pow(c1._real,2) + pow(c1._img,2)
           == pow(c2._real, 2) + pow(c2._img, 2))
            return c1._real <= c2._real;
        return pow(c1._real, 2) + pow(c1._img, 2)
            <= pow(c2._real, 2) + pow(c2._img, 2);
    }

};

void Pop(set<Complex,ComplexCmp>& s){
    if(s.size() == 0){
        cout << "empty" << endl;
        return;
    }
    // 非空
    set<Complex,ComplexCmp>::iterator it = s.end();
    it--;   // 将迭代器偏转到最后一个元素,即最大元素
    cout << it->_real << "+i" << it->_img << endl;
    s.erase(it);
    cout << "SIZE = " << s.size() << endl;
}

void Insert(set<Complex,ComplexCmp>& s, Complex c){
    s.insert(c);
    cout << "SIZE = " << s.size() << endl;
}

int main()
{
    int n;
    cin >> n;
    set<Complex,ComplexCmp> s;
    for(int i = 0; i < n; ++i){
        string op;
        cin >> op;
        if(op[0] == 'I'){   // Insert操作
            int real;
            int img;
            scanf("%d + i %d", &real, &img);
            Complex c(real, img);
            Insert(s,c);
        }else{  // Pop操作
            Pop(s);
        }
    }

    return 0;
}


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务