1030. Travel Plan (30)

Dijkstra

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int INF = 99999999;
const int MAX = 1000;
int d[MAX],G[MAX][MAX],C[MAX][MAX],cost[MAX],pre[MAX];
bool visited[MAX]={false};
int n,m,s,e;
void dijkstra(int s){
	fill(d,d+MAX,INF);
	fill(cost,cost+MAX,INF);
	d[s]=0,cost[s]=0;
	for(int i=0;i<n;i++) pre[i]=i; 
	for(int i=0;i<n;i++){
		int u=-1,mind=INF;
		for(int j=0;j<n;j++){
			if(visited[j]==false&&d[j]<mind){
				mind=d[j];
				u=j;
			}
		}
		if(u==-1) return;
		visited[u]=true;
		for(int v=0;v<n;v++){
			if(visited[v]==false&&G[u][v]!=INF){
				if(d[u]+G[u][v]<d[v]){
					d[v]=d[u]+G[u][v];
					cost[v]=cost[u]+C[u][v];
					pre[v]=u;
				}else if(d[u]+G[u][v]==d[v]&&cost[u]+C[u][v]<cost[v]){
					cost[v]=cost[u]+C[u][v];
					pre[v]=u;
				}
			}
		}
	}
} 
vector<int> path;
void DFS(int end){
	if(end==s){
		path.push_back(end);
		return ;
	}
	DFS(pre[end]);
	path.push_back(end);
} 
int main(){
	fill(G[0],G[0]+MAX*MAX,INF);
	fill(C[0],C[0]+MAX*MAX,INF);
	scanf("%d%d%d%d",&n,&m,&s,&e);
	for(int i=0;i<m;i++){
		int x,y,length,fee;
		scanf("%d%d%d%d",&x,&y,&length,&fee);
		G[x][y]=G[y][x]=length;
		C[x][y]=C[y][x]=fee;	
	}
	dijkstra(s);
	DFS(e);
	for(int i=0;i<path.size();i++){
		if(i!=0) printf(" ");
		printf("%d",path[i]);
	}
	printf(" %d %d",d[e],cost[e]);
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值