单源最短路径

 

#include<iostream>
#include<algorithm>
#include<queue>
#define MAX 1000000 
#define MAXInt 31245
using namespace std;
typedef pair<int,int> Pair;//用优先队列选取权重最小的节点 
priority_queue<Pair,vector<Pair>,greater<Pair> >que;
typedef struct ArcNode{
	int adjvex;
	int weight;
	struct ArcNode* nextarc;
}ArcNode;
typedef struct VNode{
	bool vis;
	int wei;//用pair存的值<weight,该权重的节点> 
	ArcNode *firstarc;
}VNode;
typedef struct{
	VNode* vertice;
	int vexnum,arcnum;
}ALGraph;
void Creat(ALGraph &G){
	G.vertice=new VNode[MAX];
	for(int k=0;k<MAX;k++){
		G.vertice[k].firstarc=NULL;
		G.vertice[k].vis=false;
		G.vertice[k].wei=MAXInt;
	}
	for(int i=0;i<G.arcnum;i++){
		int v1,v2,wei;
		cin>>v1>>v2>>wei;
	    ArcNode *pe=new ArcNode;
	    pe->adjvex=v2;
	    pe->weight=wei;
	    pe->nextarc=G.vertice[v1].firstarc;
	    G.vertice[v1].firstarc=pe; 
	}
} 
void Dij(ALGraph &G,int s){
	G.vertice[s].wei=0;
	que.push(Pair(0,s));
	while(!que.empty()){
		Pair tmp=que.top();
		que.pop();
		int v=tmp.second;//节点 
		int w=tmp.first;//权重 
		if(G.vertice[v].vis==true)
		    continue;
		else
		G.vertice[v].vis=true;
		ArcNode *p=G.vertice[v].firstarc;
		while(p!=NULL){
				int v0=p->adjvex;
				if(w+p->weight<G.vertice[v0].wei&&!G.vertice[v0].vis){
					G.vertice[v0].wei=G.vertice[v].wei+p->weight;
					que.push(Pair(G.vertice[v0].wei,v0));
				}
				p=p->nextarc; 
        }	
    }	
}
int main(){
	/* 
		11 0 8
0 1 6
0 2 4
0 3 5
1 4 1
2 4 1
3 5 2
4 6 9
4 7 7
5 7 4
6 8 2
7 8 4
*/
	ALGraph G;
	int s,e;
	cin>>G.arcnum>>s>>e;//输入边数,起点,终点 
	Creat(G);
	Dij(G,s);
	if(G.vertice[e].wei!=MAXInt)
	cout<<G.vertice[e].wei<<endl;
	else
	cout<<-1<<endl;
	delete []G.vertice;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值