当前位置: 首页 > 工具软件 > queue-fun > 使用案例 >

求质因数个数,结构体中调用方法this->fun(), 运算符重载

宋康安
2023-12-01

3345:priority queue练习题

传送门

#include <bits/stdc++.h>
using namespace std;

struct node{
	int num;
	int zys;
	node(){
		num=0;zys=0;
	}
	node(int n){
		this->num=n;
		this->zys=0;
		this->fun(n);
	}
	
	void fun(int n){
	int t=n;
	int i=2;
	int cnt=0;
	while(t!=1){
		if(t%i==0&&i!=n)cnt++;
		while(t%i==0)t/=i;
		i++;
	} 
	this->zys=cnt;
}
	bool operator<(const node& n)const{
		if(zys==n.zys)return num<n.num;
		return zys<n.zys;
	}
	bool operator>(const node& n)const{//重载>是为了priority_queue中greater<node> 
		return n<*this;
	}
};
int main(){
	priority_queue<node> p1;
	priority_queue<node,vector<node>,greater<node> >p2;
//	ios::sync_with_stdio(false);
//	cin.tie(0); 
	int n;
	cin>>n;
	int m;
	while(n--){
		for(int i=1;i<=10;i++){
		cin>>m;
		p1.push(node(m));
		p2.push(node(m));
	}
	cout<<p1.top().num<<" "<<p2.top().num<<endl;
	p1.pop();p2.pop();
	}

    return 0;
}

求质因数的个数

int n;
cin>>n;
int i=2; int t=n; int cnt=0;
while(t!=1){
	//while(t%i==0)t/=i;这两句顺序搞反就完蛋
	if(t%i==0&&i!=n)cnt++;
	while(t%i==0)t/=i;
	i++;
}
cout<<cnt<<endl;

结构体初始化变量

node(int x,int y):x(xx),y(yy){};
node(int n){
this->num=n;
this->zys=0;
this->fun(); 调用结构体内部的函数(可以有参数),从而为结构体变量赋值
}

运算符重载

bool operator < (const node& n) const{
if(zys= =n.zys)return num<n.num;
return zyx<n.zys;
}
重载 > ,可以决定greater的排序规则

 类似资料: