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

Enjoy_process發表於2018-10-17

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;
 } 

 

相關文章