明明找的是差分约束,然后就找到这题不知道为什么是求1~n的最短路的题了。然后自己无聊写了一个heap,518ms通过。
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 6 using namespace std; 7 8 const int N = 33333; 9 const int M = 155555; 10 struct Edge { 11 int t, nx, c; 12 } edge[M]; 13 int eh[N], ec; 14 15 void init() { 16 memset(eh, -1, sizeof(eh)); 17 ec = 0; 18 } 19 20 void addedge(int s, int t, int c) { 21 edge[ec].t = t, edge[ec].nx = eh[s], edge[ec].c = c; 22 eh[s] = ec++; 23 } 24 25 struct Heap { 26 int val[N], pos[N], id[N], sz, tmp, d; 27 void init() { 28 sz = 0; 29 memset(pos, -1, sizeof(pos)); 30 } 31 int up(int t) { 32 while (t > 1 && val[t] < val[t >> 1]) pos[id[t] = id[t >> 1]] = t, swap(val[t], val[t >> 1]), t >>= 1; 33 return t; 34 } 35 void push(int i, int v) { 36 val[++sz] = v; 37 pos[i] = up(sz); 38 id[pos[i]] = i; 39 } 40 void down(int tmp) { 41 while ((tmp << 1) <= sz) { 42 if (val[tmp] <= val[tmp << 1] && val[tmp] <= val[tmp << 1 | 1]) break; 43 if ((tmp << 1 == sz) || val[tmp << 1] <= val[tmp << 1 | 1]) { 44 d = tmp << 1; 45 swap(pos[id[tmp]], pos[id[d]]); 46 swap(id[tmp], id[d]); 47 swap(val[tmp], val[d]); 48 tmp = d; 49 } else { 50 d = tmp << 1 | 1; 51 swap(pos[id[tmp]], pos[id[d]]); 52 swap(id[tmp], id[d]); 53 swap(val[tmp], val[d]); 54 tmp = d; 55 } 56 } 57 } 58 void modify(int i, int v) { 59 val[pos[i]] = v; 60 down(pos[i]); 61 pos[i] = up(pos[i]); 62 id[pos[i]] = i; 63 } 64 void pop(int &i) { 65 if (sz == 0) { 66 i = -1; 67 return ; 68 } 69 i = id[1]; 70 pos[i] = -1; 71 if (sz == 1) { sz--; return ;} 72 val[1] = val[sz]; 73 id[1] = id[sz]; 74 pos[id[1]] = 1; 75 sz--; 76 if (sz > 0) down(1); 77 } 78 int gv(int i) { return ~pos[i] ? val[pos[i]] : -1;} 79 } hp; 80 int dis[N]; 81 82 int dij(int s, int t) { 83 int cur, i; 84 hp.init(); 85 memset(dis, 127, sizeof(dis)); 86 dis[s] = 0; 87 hp.push(s, 0); 88 while (hp.sz) { 89 hp.pop(cur); 90 if (cur == t) return dis[cur]; 91 for (i = eh[cur]; ~i; i = edge[i].nx) { 92 Edge &e = edge[i]; 93 if (dis[e.t] > dis[cur] + e.c) { 94 dis[e.t] = dis[cur] + e.c; 95 if (~hp.gv(e.t)) hp.modify(e.t, dis[e.t]); 96 else hp.push(e.t, dis[e.t]); 97 } 98 } 99 } 100 return -1; 101 } 102 103 int main() { 104 int x, y, v; 105 int n, m; 106 while (~scanf("%d%d", &n, &m)) { 107 init(); 108 while (m--) { 109 scanf("%d%d%d", &x, &y, &v); 110 addedge(x, y, v); 111 } 112 printf("%d ", dij(1, n)); 113 } 114 return 0; 115 }
——written by Lyon