ZCMU_1200 小明的难题

Description

image-20250510205607169

Input

image-20250510205633136

Output

image-20250510205643660

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

Hint

最短路径 dijkstra 算法

Personal Solution

#include<bits/stdc++.h>
using namespace std;
const int INF=1e9;
const int MAXV=1010;


int G[MAXV][MAXV];
int d[MAXV];

bool vis[MAXV]={false};
int n,m;

void Dij(int st){
	fill(d,d+MAXV,INF);
	fill(vis,vis+MAXV,false);
	d[st]=0;
	//vis[st]=true;
	for(int i=1;i<=n;i++){
		int u=-1;
		int MIN=INF;
		for(int j=1;j<=n;j++){
			if(vis[j]==false&&d[j]<MIN){
				u=j;
				MIN=d[j];
			}
		}
		if(u==-1) return;
		vis[u]=true;
		for(int v=1;v<=n;v++){
			if(vis[v]==false&&G[u][v]+d[u]<d[v]){
				d[v]=d[u]+G[u][v];
			}
		}
	}
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		scanf("%d%d",&n,&m);
		fill(G[0],G[0]+MAXV*MAXV,INF);
		for(int i=0;i<m;i++){
			int a,b,x;
			scanf("%d%d%d",&a,&b,&x);
			G[a][b]=min(G[a][b],x),G[b][a]=G[a][b];
		}
		int st,ed;
		scanf("%d%d",&st,&ed);
		Dij(st);
		if(d[ed]!=INF) printf("%d\n",d[ed]);
		else printf("-1\n");
	}
	return 0;
}
posted @ 2025-05-10 21:02  Yygz314  阅读(16)  评论(0)    收藏  举报