dijkstra之zkw线段树优化

匿名 (未验证) 提交于 2019-12-02 23:32:01

其实特别好理解,我们只要写一个数据结构(线段树)支持一下操作:
1.插入一个数\(x\)
2.查询当前数据结构中最小的数的插入编号。
3.删除插入编号为\(x\)的数。

第一眼看成可持久化了
其实就是一个单点修改,区间(全局)查询的线段树。
zkw线段树在普通线段树的基础上进行了优化(卡常神器)。
我们记录每一个点在线段树中叶子节点的编号。这样修改的时候就不用递归下去找了,直接一个while循环pushup上来就完事。

#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<cstdlib> #include<cctype> #include<vector> #include<stack> #include<queue> using namespace std; #define enter puts("")  #define space putchar(' ') #define Mem(a, x) memset(a, x, sizeof(a)) #define In inline typedef long long ll; typedef double db; const int INF = 0x3f3f3f3f; const db eps = 1e-8; const int maxn = 1e5 + 5; inline ll read() {     ll ans = 0;     char ch = getchar(), last = ' ';     while(!isdigit(ch)) last = ch, ch = getchar();     while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();     if(last == '-') ans = -ans;     return ans; } inline void write(ll x) {     if(x < 0) x = -x, putchar('-');     if(x >= 10) write(x / 10);     putchar(x % 10 + '0'); }  int n, m, s; struct Edge {     int nxt, to, w; }e[maxn << 1]; int head[maxn], ecnt = -1; In void addEdge(int x, int y, int w) {     e[++ecnt] = (Edge){head[x], y, w};     head[x] = ecnt; }  int Min[maxn << 2], id[maxn << 2], pos[maxn << 2]; In void pushup(int now) {     if(Min[now << 1] <= Min[now << 1 | 1]) Min[now] = Min[now << 1], id[now] = id[now << 1];     else Min[now] = Min[now << 1 | 1], id[now] = id[now << 1 | 1]; } In void build(int L, int R, int now) {     if(L == R)      {         Min[now] = INF; id[now] = L;          pos[L] = now;         return;     }     int mid = (L + R) >> 1;     build(L, mid, now << 1), build(mid + 1, R, now << 1 | 1);     pushup(now); } In void update(int now, int d) {     Min[now] = d;     while(now >> 1) pushup(now >> 1), now >>= 1; }  bool in[maxn]; int dis[maxn]; In void dijkstra(int s) {     Mem(dis, 0x3f), dis[s] = 0;     update(pos[s], dis[s]);     while(Min[1] ^ INF)     {         int now = id[1]; update(pos[now], INF);         if(in[now]) continue;         in[now] = 1;         for(int i = head[now], v; ~i; i = e[i].nxt)         {             if(dis[v = e[i].to] > dis[now] + e[i].w)             {                 dis[v] = dis[now] + e[i].w;                 update(pos[v], dis[v]);             }         }     } }  int main() {     Mem(head, -1);     n = read(), m = read(), s = read();     build(1, n, 1);     for(int i = 1; i <= m; ++i)     {         int x = read(), y = read(), w = read();         addEdge(x, y, w);     }     dijkstra(1);     for(int i = 1; i <= n; ++i) write(dis[i]), space; enter;     return 0; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!