POJ 2387 Til the Cows Come Home

题目大意:

题目链接

注释代码:

无注释代码:

#include <iostream>
#include <cstdio>
#include <queue>

#define	INF		1000000

#define	MAXN	1000
#define	MAXM	4000

using namespace std;

struct	Arc {

	int		v;
	int		c;

	Arc(void) {}
	Arc(int vv, int cc) : v(vv), c(cc) {}
};

struct	Node {

	int		u;
	int		d;

	Node(void) {}
	Node(int uu, int dd) : u(uu), d(dd) {}

	bool
	operator<(const Node &oth)
	const {
	
		return d > oth.d;
	}
};

Arc		arc[MAXM + 1];
int		head[MAXN + 1];
int		nxt[MAXM + 1];
int		e;

int		dis[MAXN + 1];
bool	vis[MAXN + 1];

priority_queue<Node>	heap;

void
addarc( int u, int v, int c ) {

	arc[e].v = v;
	arc[e].c = c;

	nxt[e]  = head[u];
	head[u] = e++;
}

int
dij(int n) {

	int		u, v;
	int		i;

	Node	node;

	for ( i = 1; i <= n; i++ ) dis[i] = INF;

	heap.push(Node(1, 0));
	dis[1] = 0;
	while (true) {
	
		node = heap.top();
		heap.pop();

		if ( ( u = node.u ) == n ) return dis[n];
		if ( vis[u] ) continue;

		vis[u] = true;
		for ( i = head[u]; i; i = nxt[i] )
			if ( !vis[ v = arc[i].v ] && dis[u] + arc[i].c < dis[v] ) {
			
				dis[v] = dis[u] + arc[i].c;
				heap.push(Node(v, dis[v]));
			}
	}

	return -1;
}

int
main() {

	int		n, m;
	int		u, v, c;

	e = 1;
	scanf("%d%d", &m, &n);
	while ( m-- ) {
	
		scanf("%d%d%d", &u, &v, &c);
		addarc( u, v, c );
		addarc( v, u, c );
	}
	printf("%d\n", dij(n));

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值