跳到正文

个人记录

dijksta堆优化

Marvel26约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年9月28日
收录
2025年12月12日
更新
2026年10月8日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前
C++
#include<bits/stdc++.h>
#define M 100005
#define N 20005
using namespace std;
int n,m,maxn=-1,sum=0,ans;
struct node{
	int v,w,nxt;
}e[M];
int head[N],k=0;
int dis[N];
bool vis[N];
struct point{
	int x,id;
	bool operator > (const point &tmp) const{
		return x>tmp.x;
	}
};
priority_queue<point,vector<point>,greater<point> > q;
int read(){
	int x=0;char ch;
	ch=getchar();
	while(ch<'0' || ch>'9') ch=getchar();
	while(ch>='0' && ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
	return x;
}
void add(int ui,int vi,int wi){
	e[++k].v=vi;e[k].w=wi;e[k].nxt=head[ui];
	head[ui]=k;
}
void dijk(){
	memset(dis,0x3f,sizeof(dis));
	memset(vis,0,sizeof(vis));
	dis[1]=0;
	q.push({0,1});
	while(!q.empty()){
		int ui=q.top().id;q.pop();
		if(vis[ui]) continue;
		vis[ui]=1;
		for(int i=head[ui];i;i=e[i].nxt){
			int vi=e[i].v;
			if(dis[vi]>e[i].w+dis[ui]){
				dis[vi]=e[i].w+dis[ui];
				q.push({dis[vi],vi});
			}
		}
	}
}
int main(){
	n=read();m=read();
	for(int i=1;i<=m;++i){
		int ui=read(),vi=read();
		add(ui,vi,1);add(vi,ui,1);
	}
	dijk();
	for(int i=2;i<=n;++i){
		if(maxn<dis[i]) maxn=dis[i],ans=i;
	}
	for(int i=2;i<=n;++i){
		if(dis[i]==maxn) sum++;
	}
	printf("%d %d %d\n",ans,maxn,sum);
	return 0;
}
原文
抓取于
  1. Marvel2

    Jerk!!

  2. chl090410

    asshole

  3. chl090410

    Such an ass!!!