zcmu-1624: 最短路(dijkstra)

Description

有n个城市编号为1—n,m条路,告诉你每条路的长度,求给定两点的最短路径长度。

Input

T 组数据

每组数据第一行有两个正整数n,m(n<=1000,m<=10000)分别表示城市的数量和路的条数,接下来m行,每行3个整数a,b,c,表示城市a和城市b之间有一条c长度的路

最后一行输入两个整数x,y。

Output

输出城市 x 到城市 y 的最短路径。如果不存在输出-1。

Sample Input

2

3 2

1 2 2

2 3 3

1 3

4 2

1 2 3

1 3 2

1 4

Sample Output

5

-1

注释:输入的数据中存在重边,那么就要在输入的时候判断一下,取最小值,本题数据不是很大,所以代码不需要优化,用最原始的就行。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
const int inf=0x3f3f3f3f;
int t,n,m,a,b,c,x,y;
int dist[maxn],p[maxn],dp[maxn][maxn];
bool flag[maxn];
void dijkstra(int u){
	for(int i=1;i<=n;i++){
		dist[i]=dp[u][i];
		flag[i]=false;
		if(dist[i]==inf){
			p[i]=-1;
		}
		else p[i]=u;
	}
	dist[u]=0;
	flag[u]=true;
	for(int i=1;i<n;i++){
		int temp=inf,t=u;
		for(int j=1;j<=n;j++){
			if(dist[j]<temp&&!flag[j]){
				temp=dist[j];
				t=j;
			}
		}
		if(t==u)return ;
		flag[t]=true;
		for(int j=1;j<=n;j++){
			if(dist[j]>dist[t]+dp[t][j]&&!flag[j]){
				dist[j]=dist[t]+dp[t][j];
				p[j]=t;
			}
		}
	}
	
}
int main(){
	while(~scanf("%d",&t)){
		while(t--){
			scanf("%d %d",&n,&m);
			memset(dp,inf,sizeof(dp));
			memset(flag,false,sizeof(flag));
			for(int i=0;i<m;i++){
				scanf("%d %d %d",&a,&b,&c);
				dp[a][b]=min(dp[a][b],c);dp[b][a]=min(dp[b][a],c);//特判
			}
			scanf("%d %d",&x,&y);
			dijkstra(x);
			if(dist[y]==inf)cout<<"-1\n";
			else cout<<dist[y]<<endl;
		}
	}
} 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

emo的鱼香roise

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

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

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

打赏作者

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

抵扣说明:

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

余额充值