Dijkstra裸题

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
const int nmax=2000,mmax=2010;
int n,m;
int maps[nmax][nmax];
int dist[nmax];
bool vis[nmax];
void dijkstra(){
	dist[1] = 0;
	for(int i=0;i<n-1;i++){
		int t = -1;
		for(int j = 1;j<=n;j++){
			if(!vis[j]&&(t==-1||dist[j]<dist[t]))
				t = j;
		}
		vis[t] = true;
		for(int j=1;j<=n;j++){
			dist[j] = min(dist[j],dist[t]+maps[t][j]);
		}
	}
}
int main(){
	scanf("%d%d",&m,&n);
	memset(maps,0x3f,sizeof(maps));
	memset(dist,0x3f,sizeof(dist));
	memset(vis,false,sizeof(vis));
	for(int i=0;i<m;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		if(maps[u][v]>w){
			maps[u][v]=w;
			maps[v][u]=w;
		}
	}
	dijkstra();
	cout<<dist[n];
}

优先队列优化

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int ,int >PII;
int n,m;
const int N =1.5e5+10;
int w[N],e[N],ne[N],dist[N],h[N],idx;
bool st[N];
void add(int a,int b,int c){
    e[idx]=b;
    ne[idx]=h[a];
    h[a]=idx;
    w[idx]=c;
    idx++;
}
int dijkstra(){
    memset(dist,0x3f,sizeof(dist));
    priority_queue<PII,vector<PII>,greater<PII> >heap;
    dist[1]=0;
    heap.push({0,1});
    while(heap.size()){
        auto t = heap.top();
        heap.pop();
        int distance =t.first,num=t.second;
        if(st[num])continue;
        st[num]=true;
        for(int i=h[num];i!=-1;i=ne[i]){
            int other=e[i];
            if(dist[other]>distance+w[i]){
                dist[other]=distance+w[i];
                heap.push({dist[other],other});
            }
            
        }
    }
    if(dist[n]==0x3f3f3f3f)return -1;
    return dist[n];
}
int main(){
    scanf("%d%d",&n,&m);
    memset(h,-1,sizeof(h));
    memset(st,false,sizeof(st));
    while(m--){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    cout<<dijkstra()<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@居安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值