/**
* @file main.cpp
* @brief 差分约束系统,题意大致如下:
* 1号小孩叫snoopy,N号小孩叫flymouse
* N号小孩希望自己的糖果要比1号小孩尽量的多
* 但是需要满足特定约束:
*
* 设s[i]为i号小孩的糖数,对于约束(a,b,c)的含义是
* s[b] - s[a] <= c
*
* 即:
* if (s[a] + c < s[b])
* s[b] = s[a] + c
*
* 所以构图是在(a,b)添加权值c,求最小路径s[n]
*
* @author yekeren
* @version 1.0.0
* @date 2013-06-06
*/
#include <stdio.h>
#include <queue>
#define LIMIT 31000
#define MAX_INT 0x7fffffff
///(M)临接表
struct edge_t
{
int b, c;
struct edge_t *next;
};
edge_t *k[LIMIT] = { NULL };
edge_t pool[LIMIT * 100];
int npool = 0;
///(M)堆数据
struct item_t {
int d, i;
};
class lessto
{
public:
bool operator()(const item_t &i1, const item_t &i2) const
{
return (i1.d > i2.d);
}
};
/**
* @brief 添加边
* @param a
* @param b
* @param c
*/
void add_edge(int a, int b, int c)
{
pool[npool].next = k[a];
pool[npool].b = b;
pool[npool].c = c;
k[a] = &pool[npool++];
}
/**
* @brief shortest path faster algorithm
* @param n
* @return
*/
int dijstra(int n)
{
int s[LIMIT] = { 0 };
for (int i = 1; i <= n; ++i) {
s[i] = MAX_INT;
}
std::priority_queue<item_t, std::vector<item_t>, lessto> q;
unsigned char visit[LIMIT] = { 0 };
s[1] = 0;
item_t t;
t.d = 0;
t.i = 1;
q.push(t);
while (!q.empty())
{
t = q.top();
q.pop();
int u = t.i;
if (visit[u]) { //注意这里,重复边的处理
continue;
}
visit[u] = 1;
for (edge_t *p = k[u]; p != NULL; p = p->next)
{
int v = p->b;
int c = p->c;
if (s[u] + c < s[v])
{
s[v] = s[u] + c;
t.d = s[v];
t.i = v;
q.push(t);
}
}
}
return s[n];
}
int main(int argc, char *argv[])
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add_edge(a, b, c);
}
printf("%d\n", dijstra(n));
return 0;
}