关于运算符重载
查看原帖
关于运算符重载
107568
Ayaka_T楼主2022/4/7 14:14

Rt,dij这样重载是可以通过的:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
struct node{
	int to,v;
	bool operator < (const node &x)const
	{
		return x.v<v;
	}
};
vector<node>d[maxn];
priority_queue<node>q;
int n,m,s,u,v,to,ans[maxn];
bool vis[maxn];
void dij(){
	memset(ans,0x3f,sizeof ans);
	ans[s]=0;
	q.push({s,0});
	while(!q.empty()){
		node now=q.top();
		q.pop();
		if(vis[now.to])continue;
		vis[now.to]=true;
		for(int i=0;i<d[now.to].size();i++){
			node next=d[now.to][i];
			if(ans[next.to]>ans[now.to]+next.v){
				ans[next.to]=ans[now.to]+next.v;
				q.push({next.to,ans[next.to]});
			}
		}
	}
	for(int i=1;i<=n;i++){
		printf("%d ",ans[i]);
	}
}
int main(){
	scanf("%d%d%d",&n,&m,&s);
	for(int i=1;i<=m;i++){
		scanf("%d%d%d",&u,&v,&to);
		d[u].push_back({v,to});
	}
	dij();
	return 0;
}

而将重载的部分改为这样:

friend const bool operator <(node x,node y){
	return x.v<y.v;
}

就无法通过

改成这样就可以通过:

friend bool operator<(node x,node y){
	if(x.v<y.v)
		return false;
	else 
		return true;
}

或这样也可以

friend bool operator<(node x,node y)
{
	return x.v>y.v;
}

问题:

1,为什么定义大根堆要重载小于号

2,为什么用友元重载时,函数内就要反着过来

望解答,谢谢!

2022/4/7 14:14
加载中...