llllmz

导航

KY196 复数集合C++

这题难点就是什么是复数的模了吧。

然后C++写个优先队列(大根堆)+操作符重载就行了。

#include<iostream>
#include<string>
#include<queue>
#include<math.h>
using namespace std;

struct node{
    int a;
    int b;
};
typedef struct node element;

int change(string s,int& i){
    string t;
    while(i<s.size()){
        if('0'<=s[i]&&s[i]<='9'){
            t.push_back(s[i]);
            i++;
        }else{
            break;
        }
    }
    return stoi(t);
}

bool operator< (element lhand,element rhand){
    long x=pow(lhand.a,2)+pow(lhand.b,2);
    long y=pow(rhand.a,2)+pow(rhand.b,2);
    if(x>y){
        return false;
    }else if(x==y){
        if(lhand.b<rhand.b){
            return false;
        }
    }
    return true;

}

int main(){
    int n;
    while(cin >> n ){
        char c;
        while(c=getchar()!='\n');
        priority_queue<element> heap;
        while(n!=0){
            string s;
            getline(cin,s);
            if(s[0]=='P'){
                if(heap.empty()){
                    cout <<"empty" <<'\n';
                }else{
                    cout << heap.top().a <<"+i" <<heap.top().b << '\n';
                    heap.pop();
                    cout <<"SIZE = " <<heap.size()<<'\n';
                }
            }else{
                cout <<"SIZE = " <<heap.size()+1<<'\n';
                int i=0;
                int a=0,b=0;
                for(;i<s.size();i++){
                    if('0'<=s[i]&&s[i]<='9'){
                        a=change(s,i);
                        break;
                    }
                }
                i++;
                for(;i<s.size();i++){
                    if('0'<=s[i]&&s[i]<='9'){
                        b=change(s,i);
                        break;
                    }
                }
                element* tem=new element ;
                tem->a=a;
                tem->b=b;
                heap.push(*tem);
            }
            n--;
        }
    }
    return 0;
}

结果如下:

posted on 2024-01-25 15:36  神奇的萝卜丝  阅读(29)  评论(0)    收藏  举报