虚数
利用大根堆
题目描述
一个复数(x+iy)集合,两种操作作用在该集合上: 1、Pop 表示读出集合中复数模值最大的那个复数,如集合为空 输出 empty ,不为空就输出最大的那个复数并且从集合中删除那个复数,再输出集合的大小SIZE; 2 Insert a+ib 指令(a,b表示实部和虚部),将a+ib加入到集合中 ,输出集合的大小SIZE; 最开始要读入一个int n,表示接下来的n行每一行都是一条命令。
输入描述:
输入有多组数据。
每组输入一个n(1<=n<=1000),然后再输入n条指令。
输出描述:
根据指令输出结果。
模相等的输出b较小的复数。
a和b都是非负数。
示例1
输入
3
Pop
Insert 1+i2
Pop
输出
empty
SIZE = 1
1+i2
SIZE = 0
#include <string.h>
#include <stdio.h>
#include <queue>
#include <algorithm>
using namespace std;
struct Complex_num
{
int a, b;
// 使用queue排序时一定要用
// bool operator<(const Class &tmp)cosnt这种格式
bool operator<(const Complex_num &t) const
{
return a * a + b * b < t.a * t.a + t.b * t.b;
}
};
int main()
{
int T;
char str[10];
priority_queue<Complex_num> Q;
scanf("%d", &T);
while (T--)
{
scanf("%s", str);
Complex_num tmp;
if (strcmp(str, "Pop") == 0)
{
if (Q.size() == 0)
printf("empty\n");
else
{
tmp = Q.top(); //堆顶元素
printf("%d+i%d\n", tmp.a, tmp.b);
Q.pop(); //取出堆中模最大的元素
printf("SIZE = %d\n", Q.size());
}
}
else if (strcmp(str, "Insert") == 0)
{
scanf("%d+i%d", &tmp.a, &tmp.b);
Q.push(tmp); //放入堆中
printf("SIZE = %d\n", Q.size());
}
}
return 0;
}
暴力解法
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
struct E{
int x;
int y;
int mo;
}fushu[1000]; //定义复数的集合
bool cmp(E a,E b){
if(a.mo==b.mo) return a.y<b.y;
else return a.mo>b.mo;
}
int main(){
int n;
int size=0;
scanf("%d",&n); //输入n条指令
bool mark[1001];
for(int i=0;i<=1000;i++)
mark[i]=false;
while(n--){
char str[10];
scanf("%s",str);
if(strcmp(str,"Pop")==0){
int flag=0;
for(int i=0;i<size;i++){
if(mark[i]==true){
flag=1;
break;
}
}
if(flag==0)
printf("empty\n");//判空
else{
sort(fushu,fushu+size,cmp); //排序
printf("%d+i%d\n",fushu[0].x,fushu[0].y);//输出
if(size==1){
size--;
mark[size]=false;
}
else{
for(int i=1;i<size;i++){ //删除
fushu[i-1]=fushu[i];
}
size--;
mark[size]=false;
}
printf("SIZE = %d\n",size); //输出大小
}
}
else{
E temp; //插入到数组中
scanf("%d+i%d",&temp.x,&temp.y);
temp.mo=sqrt(temp.x*temp.x+temp.y*temp.y);
fushu[size]=temp;
mark[size]=true;
size++;
printf("SIZE = %d\n",size); //输出大小
}
}
return 0;
}