[kuangbin带你飞]专题四 最短路练习 题解

专题四 最短路练习 
POJ 2387 Til the Cows Come Home
POJ 2253 Frogger
POJ 1797 Heavy Transportation
POJ 3268 Silver Cow Party
POJ 1860 Currency Exchange
POJ 3259 Wormholes
POJ 1502 MPI Maelstrom
POJ 3660 Cow Contest
POJ 2240 Arbitrage
POJ 1511 Invitation Cards
POJ 3159 Candies
POJ 2502 Subway
POJ 1062 昂贵的聘礼
POJ 1847 Tram
LightOJ 1074 Extended Traffic
HDU 4725 The Shortest Path in Nya Graph
HDU 3416 Marriage Match IV
HDU 4370 0 or 1
POJ 3169 Layout

 

POJ 2387 Til the Cows Come Home 

描述

Bessie在外地,想要回到谷仓,尽可能多地睡觉,然后Farmer John在早上挤奶时将她叫醒。贝茜需要她的美丽睡眠,所以她想尽快回来。 

Farmer John的场地中有N(2 <= N <= 1000)个地标,唯一编号为1..N。地标1是谷仓; Bessie整天站立的苹果树林是具有里程碑意义的N.奶牛在田间旅行时使用T(1 <= T <= 2000)双向牛尾迹,各种长度的地标之间。Bessie对她的导航能力没有信心,所以一旦她开始,她总是会从开始到结束。 

鉴于地标之间的路径,确定贝西必须走的最小距离才能回到谷仓。保证存在一些这样的路线。

输入

*第1行:两个整数:T和N 

*第2行...... T + 1:每行描述一个以三个以空格分隔的整数的轨迹。前两个整数是小道行进的地标。第三个整数是路径的长度,范围是1..100。

产量

*第1行:一个整数,是Bessie从地标N到地标1必须经过的最小距离。

样本输入

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

样本输出

90

暗示

输入细节: 

有五个地标。 

输出细节: 

贝茜可以通过以下第4,3,2和1路回家。

 

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

struct edge{
    int to,cost;
};
typedef pair P;//first是最短距离,second是顶点的编号

const int N = 1005;
const int INF = 99999999;
vector G[N];
int dis[N];
int n,m,x,y,w;

void dijkstra(int s){
    priority_queue, greater

> pq;//通过greater

参数,堆按照first从小到大的顺序取出值 fill(d,d+N,INF); d[s] = 0; pq.push(P(0,s)); while(!pq.empty()){ P p = pq.top(); pq.pop(); int v = p.second; if(d[v]d[v]+e.cost){ d[e.to] = d[v] + e.cost; pq.push(P(d[e.to],e.to)); } } } printf("%d\n",d[n]); } void init(int n){ for(int i=0;i<=n;i++) G[i].clear(); } void addedge(int u,int v,int w){ G[u].push_back({v,w}); } int main(){ while(~scanf("%d%d",&m,&n)){ init(n); for(int i=1;i<=m;i++){ scanf("%d%d%d",&x,&y,&w); addedge(x,y,w); addedge(y,x,w); } dijkstra(1); // for(int i=1;i<=n;i++) // printf("%d:%d\n",i,d[i]); } return 0; }

 

 

 

 

 

 

你可能感兴趣的:(图论,最短路)