码迷,mamicode.com
首页 > 其他好文 > 详细

【模板】图论

时间:2018-11-08 13:44:05      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:链式前向星   return   class   tin   mem   top   优化   算法   build   

基础图论

链式前向星

带权值

int head[400001],ver[2000001],nxt[2000001],val[2000001],tot=0;
void add(int x,int y,int z) {
    ver[++tot]=y,val[tot]=z,nxt[tot]=head[x],head[x]=tot;
    ver[++tot]=x,val[tot]=z,nxt[tot]=head[x],head[x]=tot;
}

不带权值

int head[100001]={0},nxt[400001],ver[400001],tot=0;
void add(int x,int y) {
    ver[++tot]=y,nxt[tot]=head[x],head[x]=tot;
    ver[++tot]=x,nxt[tot]=head[y],head[y]=tot;
}

最短路算法

SPFA

int d[100001];
bool iq[100001] = {0};
queue<int>q;
void spfa(int s) {
    memset(d, 0x7f, sizeof(d));
    d[s] = 0;
    q.push(s);
    while(! q.empty()) {
        s = q.front(), q.pop();
        iq[s] = 0;
        for(int i = head[s]; i; i = nxt[i])
            if(d[ver[i]] > d[s] + val[i]){
                d[ver[i]] = d[s] + val[i];
                if(! iq[ver[i]])iq[ver[i]] = 1, q.push(ver[i]);
        }
    }
}

堆优化迪杰斯特拉

int d[100001];
bool v[100001];
priority_queue<pair<int,int> >q;
void dij(int s) {
    memset(d, 0x7f, sizeof(d));
    d[s] = 0;
    q.push(make_pair(0, s));
    while(! q.empty()) {
        s = q.top().second, q.pop();
        if(v[s])continue;
        v[s] = 1;
        for(int i = head[s]; i; i = nxt[i])
            if(d[ver[i]] > d[s] + val[i])
                q.push(make_pair(-(d[ver[i]] = d[s] + val[i]), ver[i]));
    }
}

高级图论

线段树优化连边

(非递归线段树)

int N=1;
void build(int n) {
    for(;N <= n + 1; N <<= 1);
    for(int i = N - 1; i >= 1; i --)
        add(i, i << 1 | 1, 0), add(i, i << 1, 0)
}
int find(int x) {
    return x + N;
}
void add_tree(int s, int t, int x, int v) {
    x = find(x);
  for(s = N + s - 1, r = N + r + 1; s ^ r ^ 1; s >>= 1, r >>= 1) {
      if(~ s & 1)add(x, s ^ 1, v);
      if(r & 1)add(x, r ^ 1, v);
  }
}

【模板】图论

标签:链式前向星   return   class   tin   mem   top   优化   算法   build   

原文地址:https://www.cnblogs.com/akakw1/p/9928478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!