POJ-2387 Til the Cows Come Home(最短路问题)

原题链接: http://poj.org/problem?id=2387

在这里插入图片描述
测试样例

Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90

Hint

INPUT DETAILS:
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.

题意: 求1到n的最短路径。

解题思路: 单源点最短路径问题,所以我们使用Floyd算法肯定会超时(但我比赛的时候还是信仰的交了一发哈哈),在此题中我们需要使用Dijkstra算法解决,相当于一道模板题,值得注意的是这题有重边,我们需要取最优边。如果你对Dijkstra算法还不太熟悉,这里指路一篇blog:Dijstra算法详解

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<iostream>//POJ不支持
#include<memory.h>

#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=a;i>=n;i--)

using namespace std;

const int inf=0x3f3f3f3f;//无穷大。
const int maxn=1010;//限定值。
typedef long long ll;

int t,n;
int graph[maxn][maxn];
int dis[maxn];
bool vis[maxn];
void dijstra(){
	memset(vis,false,sizeof(vis));
	vis[1]=true;
	rep(i,1,n){
		dis[i]=graph[1][i];
	}
	int pos,minn;
	pos=1;
	rep(i,1,n-1){
		minn=inf;
		rep(j,1,n){
			if(dis[j]<minn&&!vis[j]){
				minn=dis[j];
				pos=j;
			}
		}
		vis[pos]=true;
		rep(j,1,n){
			if(!vis[j]&&dis[j]>dis[pos]+graph[pos][j]){
				dis[j]=dis[pos]+graph[pos][j];
			}
		}
	}
	cout<<dis[n]<<endl;
}
int main(){
	while(cin>>t>>n){
		memset(graph,inf,sizeof(graph));
		int u,v,w;
		while(t--){
			cin>>u>>v>>w;
			if(w<graph[u][v]){
				graph[u][v]=graph[v][u]=w;
			}
		}
		dijstra();
	}
	return 0;
}

posted @ 2022-03-26 16:49  unique_pursuit  阅读(21)  评论(0)    收藏  举报