题解 | #复数集合#

复数集合

https://www.nowcoder.com/practice/abdd24fa839c414a9b83aa9c4ecd05cc

#include <iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>//求次幂,是pow,不是power
//这题是假定a和b都是正整数吗?
using namespace std;

typedef struct Complex {
    int a;
    int b;
    Complex();
    Complex(int a0, int b0): a(a0), b(b0) {};
    friend bool operator<(const Complex& c1, const Complex& c2);
    friend ostream& operator<<(ostream& out, const Complex& c);
};
Complex::Complex() {
}
//一般将双目运算符重载为友元函数
priority_queue<Complex> plur;
bool operator<(const Complex& c1, const Complex& c2) {
    bool tag=false;
    if (pow(c1.a, 2) + pow(c1.b, 2) < pow(c2.a, 2) + pow(c2.b, 2)) {
        tag=true;
    } else if (pow(c1.a, 2) + pow(c1.b, 2) == pow(c2.a, 2) + pow(c2.b, 2)) {
        tag=c1.b > c2.b;//!!输出b较小的
    }//不用再有else了
    return tag;
}

ostream& operator<<(ostream& out, const Complex& c) {
    out << c.a << "+i" << c.b;
    return  out;
}
int Insert(string str) {
    int pos = str.find('i');
    string stra = str.substr(0, pos - 1); //不包括第二个位置的数
    string strb = str.substr(pos + 1);
//    cout<<"a="<<stra<<"b="<<strb<<endl;
    int a = 0, b = 0;
    for (int i = 0; i < stra.size(); i++) {
        a = a * 10 + stra[i] - '0';

    }
//    cout<<a<<endl;
    for (int j = 0; j < strb.size(); j++) {
        b = b * 10 + strb[j] - '0';
    }
//    cout<<b<<endl;
    Complex s = Complex(a, b);
    plur.push(s);
    return plur.size();
}

string counterpart(string str) {
    string strRes;

    if (str[0] == 'P') {
        strRes = str;

    } else if (str[0] == 'I') {

        strRes = str.substr(7);

    }

    return strRes;
}

int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        cin.ignore();
        //!!!scanf函数或cin函数有回车符,
        //使用getline会导致直接跳过,所以要在这里加上cin.ignore()
        while (n > 0) {

            string str;
            getline(cin, str);
            string commend = counterpart(str);

            if (commend == "Pop") {
                if (plur.empty()) {
                    cout << "empty" << endl; //加endl换行
                } else {
                    Complex res = plur.top();
                    plur.pop();
                    cout << res << endl;;
                    cout << "SIZE = " << plur.size() << endl;

                }
            } else {
                cout << "SIZE = " << Insert(commend) << endl;
            }
            n--;
        }
    }
    return 0;
}

全部评论

相关推荐

躺尸修仙中:因为很多92的也去卷中小厂,反正投递简历不要钱,面试不要钱,时间冲突就推,不冲突就面试积累经验
点赞 评论 收藏
分享
Noel_:中石油是这样的 哥们侥幸混进免笔试名单 一看给我吓尿了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务