POJ2387 Til the Cows Come Home【最短路 Dijkstra算法】

Til the Cows Come Home

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 76034   Accepted: 25315

Description

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible. 

Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it. 

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

Input

* Line 1: Two integers: T and N 

* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.

Output

* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

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.

Source

USACO 2004 November

问题链接:POJ2387 Til the Cows Come Home

问题描述:Bessie在n号结点,他想早点回到1号结点睡觉,给定n个结点,t条双向边,问Bessie回到1号结点的最短路径是多少。

解题思路:使用dijkstra算法,程序中使用vector实现图的邻接表

AC的C++程序:

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>

using namespace std;
const int N=1005;
const int INF=0x3f3f3f3f;
int dist[N];//存储各结点到源点的最短路径 
bool vis[N];//表示结点的最短路径是否已经找到 

//边 
struct Edge{
	int v,c;//本结点到结点v的距离为c 
	Edge(int v,int c):v(v),c(c){}
};

struct Node{
	int u,c;//结点u到源点的最短距离为c
	Node(int u,int c):u(u),c(c){}
	bool operator<(const Node &a)const
	{
		return c>a.c;
	} 
};

vector<Edge>g[N];//图的邻接表表示

void dijkstra(int s)
{
	memset(vis,false,sizeof(vis));
	memset(dist,INF,sizeof(dist));
	dist[s]=0;
	priority_queue<Node>q;
	q.push(Node(s,0));
	while(!q.empty()){
		Node f=q.top();
		q.pop();
		int u=f.u;
		if(!vis[u]){//如果还未使用结点u进行松弛操作 
			vis[u]=true;
			for(int i=0;i<g[u].size();i++){//遍历与结点u相连的结点 
			int v=g[u][i].v;
			if(vis[v])//如果结点v的最短路径已经找到则跳过 
			  continue;
			int cost=g[u][i].c;//结点u到结点v的距离 
			if(dist[v]>dist[u]+cost){//更新 
				dist[v]=dist[u]+cost;
				q.push(Node(v,dist[v]));
			  }
			}
		}
	}
} 

int main()
{
	int t,n,u,v,c;
	scanf("%d%d",&t,&n);
	while(t--){
		scanf("%d%d%d",&u,&v,&c);
		g[u].push_back(Edge(v,c));
		g[v].push_back(Edge(u,c));
	}
	dijkstra(n);
	printf("%d\n",dist[1]);
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/SongBai1997/article/details/83108285
今日推荐