dijkstra邻接矩阵和堆模板

邻接矩阵
复杂度O(|V|²)

#include<bits/stdc++.h>
using namespace std;
const int MAX_V=2005;
const int INF=9999999;
int cost[MAX_V][MAX_V];//cost[u][v]表示边(u,v)的权值(不存在这条边时设为INF) 
int d[MAX_V];//顶点s出发的最短距离 
bool used[MAX_V];//已经使用过的图 
int V;//顶点数 
//求从起点s出发到各个顶点的最短距离
void dijkstra(int s){
	fill(d,d+V,INF);
	fill(used,used+V,false);
	d[s]=0;
	
	while(true){
		int v=-1;
		//从未使用过的顶点中,选择一个距离最小的顶点
		for(int u=0;u<V;u++){
			if(!used[u]&&(v==-1||d[u]<d[v])) v=u;
		}
		if(v==-1) break;
		used[v]=true;
		for(int u=0;u<V;u++){
			d[u]=min(d[u],d[v]+cost[v][u]);
		}
	}
} 
int main(){
	int from,to,cst;
	fill(cost[0],cost[0]+2005*2005,99999);
}


O(|E|log|V|)

#include<bits/stdc++.h>
using namespace std;
struct edge{int to,cost;};
typedef pair<int,int> P;//first是最短距离,second是顶点的编号
const int MAX_V=2005;
const int INF=9999999;
int V,m;
vector<edge>G[MAX_V];
int d[MAX_V];
void dijkstra(int s){
	//通过指定greater<p>参数,堆按照first从小到大的顺序取出值
	priority_queue<P,vector<P>,greater<P>> que;
	fill(d,d+V,INF); 
	d[s]=0;
	que.push(P(0,s));
	
	while(!que.empty()){
		P p=que.top();que.pop();
		int v=p.second;
		if(d[v]<p.first) continue;
		for(int i=0;i<G[v].size();i++){
			edge e=G[v][i];
			if(d[e.to]>d[v]+e.cost){
				d[e.to]=d[v]+e.cost;
				que.push(P(d[e.to],e.to));
			}
		}
	}
	mx1=0;
	for(int i=1;i<=V;i++){
		if(mx1<d[i]) mx1=d[i];
	}
}
int main(){
	cin>>V>>m;//V是顶点数 m是边的关系 
	int from,to,cost,ans=0;
	edge in;
	for(int i=0;i<m;i++){
        scanf("%d%d%d",&from,&to,&cost);
        in.to = to; in.cost = cost;
        G[from].push_back(in);
//        in.to = from; in.cost = cost; 无向边再加这两句 
//        G[to].push_back(in);
    }
	dijkstra(x);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值