题目大意:
注释代码:
无注释代码:
#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;
}