最短路dijkstra(堆实现)

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#include<queue>
#define inf 0x3f3f3f3f
#define mxn 2002
struct point {
	int num,c;
	bool operator < ( const point & b ) const {
		return c < b.c;
	}
	bool operator > ( const point & b ) const {
		return c > b.c;
	}
};
int first[mxn], nxt[mxn], to[mxn], cost[mxn], dis[mxn], e;
void add( int u, int v, int c ) {
	to[e] = v;
	cost[e] = c;
	nxt[e] = first[u];
	first[u] = e++;
}
void dijkstra( int s ) {
	memset( dis, 0x3f, sizeof( dis ) );
	priority_queue< point, vector<point>, greater< point > > q;
	point p;
	dis[s] = 0;
	p.num = s, p.c = 0;
	q.push( p );
	while( ! q.empty() ) {
		point p1 = q.top();
		q.pop();
		if( dis[p1.num] != p1.c ) 
			continue;
		for( int i = first[p1.num]; i != -1; i = nxt[i] ) {
			int v = to[i];
			if( dis[v] > dis[p1.num] + cost[i] ) {
				dis[v] = dis[p1.num] + cost[i];
				point p2;
				p2.num = v;
				p2.c = dis[v];
				q.push( p2 );
			}
		}
	}
}
int main() {
	int n,m;
	while( scanf( "%d%d", &n, &m ) != EOF ) {
		e = 0;
		memset( first, -1, sizeof( first ) );
		for( int i = 1; i <= m; ++i ) {
			int u, v, c;
			scanf( "%d%d%d", &u, &v, &c );
			add( u, v, c );
			add( v, u, c );
		}
		int st,end;
		scanf( "%d%d", &st, &end );
		dijkstra( st );
		if( dis[end] == inf )
			printf( "-1\n" );
		else
			printf( "%d\n", dis[end] );
	}
	return 0;
}

你可能感兴趣的:(最短路dijkstra(堆实现))