用双端队列,当待加入元素小于队首元素时 加入队首, 否则 加入队尾
slf优化
if(!vis[e.v]) { if(Q.empty()) Q.push_front(e.v); else { if(d[e.v] < d[Q.front()]) Q.push_front(e.v); else Q.push_back(e.v); } vis[e.v] = 1; }
next从结构体中分离出来 用数组记录
using namespace std; const int maxn = 10010, INF = 0x7fffffff; int n, m, s, t; int head[maxn], nex[maxn << 1], d[maxn], vis[maxn], cnt; struct node { int u, v, w; }Node[maxn << 1]; void add_(int u, int v, int w) { Node[cnt].u = u; Node[cnt].v = v; Node[cnt].w = w; nex[cnt] = head[u]; head[u] = cnt++; } void add(int u, int v, int w) { add_(u, v, w); add_(v, u, w); } void spfa() { deque<int> Q; for(int i = 0; i < maxn; i++) d[i] = INF; Q.push_front(s); mem(vis, 0); d[s] = 0; vis[s] = 1; while(!Q.empty()) { int u = Q.front(); Q.pop_front(); vis[u] = 0; for(int i = head[u]; i != -1; i = nex[i]) { int v = Node[i].v; if(d[v] > d[u] + Node[i].w) { d[v] = d[u] + Node[i].w; if(!vis[v]) { if(Q.empty()) Q.push_front(v); else { if(d[v] < d[Q.front()]) Q.push_front(v); else Q.push_back(v); } vis[v] = 1; } } } } } int main() { while(scanf("%d%d", &n, &m) && n + m) { mem(head, -1); cnt = 0; int u, v, w; for(int i = 0; i < m; i++) { scanf("%d%d%d", &u, &v, &w); add(u, v, w); } s = 1, t = n; spfa(); printf("%d ", d[t]); } return 0; }