dij最短路
  • 板块学术版
  • 楼主Owenzjg
  • 当前回复2
  • 已保存回复2
  • 发布时间2022/12/10 20:04
  • 上次更新2023/10/26 23:52:48
查看原帖
dij最短路
515971
Owenzjg楼主2022/12/10 20:04
#include <bits/stdc++.h>
using namespace std;
int n,m;
struct node {
	int v,w;//顶点和边权
	
};
bool operator < (const node& a,const node& b){
	return a.w>b.w;
	//边权按照从小到大排序
	
}
#define maxn 2000+10
vector <node> g[maxn+10];
int f[maxn];
bool vis[maxn];
priority_queue < node > q;
void dfs(int x){
	for(int i=0;i<maxn;i++) f[i]=1<<30;
	f[1]=0;
	
	q.push( (node){1,0} );
	while(q.size()!=0){
		node top=q.top();
		q.pop();
		if(vis[top.v]) continue ;
		vis[top.v]=1;
		
		for(int i=0;i<g[top.v].size();i++){
			node to=g[top.v][i];
			if(f[to.v]>f[top.v]+g[top.v][i].w){
				f[to.v]=f[top.v]+g[top.v][i].w;
				q.push((node){to.v,f[to.v]});
			};
		}
	}
}
int main(){
	freopen("short.in","r",stdin);
	freopen("short.out","w",stdout);
	cin>>n>>m;
	for(int i=0;i<m;i++){
		int a,b,c;
		cin>>a>>b>>c;
		g[a].push_back((node){b,c});
	}
	dfs(1);
	if(f[n]==1<<30) cout<<-1;
	cout<<f[n];
	return 0;
}

错哪了,在线等

2022/12/10 20:04
加载中...