树和图的存储

树也一种特殊的图,图分为有向图和无向图,无向图可以看为一种特殊的有向图,所以可以化简为有向图的存储,无向图加两条边即可。
存储方式:

  • 邻接矩阵:空间比较大,适合稠密图存储
  • 邻接表:适合稀疏图的存储 ```cpp const int N = 1e5+10, M = 2*N; int h[N],e[M],ne[M],idx;

// 添加一条a指向b的边 void add(int a,int b){ e[idx] = b, ne[b] = h[a], h[a] = idx++; }

int main(){ // 初始化 memset(h,-1,sizeof h); }

  1. <a name="KNvuP"></a>
  2. # 树和图的遍历
  3. <a name="b5zhc"></a>
  4. ## 深度优先遍历
  5. ```cpp
  6. const int N = 1e5+10, M = 2*N;
  7. int h[N],e[M],ne[M],idx;
  8. // 标记状态
  9. bool vis[N];
  10. // 添加一条a指向b的边
  11. void add(int a,int b){
  12. e[idx] = b, ne[b] = h[a], h[a] = idx++;
  13. }
  14. void dfs(int u){
  15. vis[u] = true;
  16. for(int i=h[u];i!=-1;i=ne[i]){
  17. int j= e[i];
  18. if(!vis[j]) dfs(j);
  19. }
  20. }
  21. int main(){
  22. // 初始化
  23. memset(h,-1,sizeof h);
  24. return 0;
  25. }

宽度优先遍历

const int N = 100005;

int h[N], e[N * 2], ne[N * 2], idx;
bool st[N];

void bfs(){
    memset(st, false, sizeof(st));
    st[1] = true;
    queue<int> q;
    q.push(1);
    while(!q.empty()){
        int u = q.front();
        q.pop();
        for(int i = h[u]; i != -1; i = ne[i]){
            int j = e[i];
            if(st[j] == false){
                // 具体问题的逻辑

                st[j] = true;
                q.push(j);
            }
        }
    }
}

拓扑排序

bool topsort(){
    int hh = 0, tt = -1;
    for(int i=1;i<=n;i++){
        if(!degree[i]) q[++tt] = i;
    }
    while(hh<=tt){
        int t = q[hh++];
        for(int i=h[t];i!=-1;i=ne[i]){
            int j = e[i];
            degree[j]--;
            if(!degree[j]) q[++tt] = j;
        }
    }
    // 如果全部入队,则说明存在拓扑序 
    return tt==n-1;
}

有向图最短路

树和图的模板 - 图1

朴素Dijkstra算法(适合稠密图)

时间复杂度:树和图的模板 - 图2,适合正权稠密图

const int N = 510;
int g[N][N]; // 稠密图用邻接矩阵
int dist[N]; // 距离起点的距离
bool st[N]; // 标记是否找到最短距离
int n,m;

int dijkstra(){
    memset(dist,0x3f,sizeof dist);
    dist[1] = 0;
    // 循环n次
    for(int i=0;i<n;i++){
        int t = -1; // 从未找到最短距离的点的集合中找距离当前最短的点
        for(int j=1;j<=n;j++){
            if(!st[j]&&(t==-1||dist[j]<dist[t])) t = j;
        }
        st[t] = true; // 进行标记
        for(int j=1;j<=n;j++){
            dist[j] = min(dist[j],dist[t]+g[t][j]);  // 更新距离
        }
    }
    if(dist[n]==0x3f3f3f3f) return -1;  //如果第n个点路径为无穷大即不存在最短路径
    else return dist[n];

}

int main(){
    cin >> n >> m;
    // 可以避免自环
    memset(g,0x3f,sizeof g);  // 按字节初始化
    while(m--){
        int x,y,z;
        cin >> x >> y >> z;
        // 避免重边的情况
        g[x][y] = min(g[x][y],z);

    }
    cout << dijkstra()<< endl;
    return 0;
}

堆优化Dijkstra算法(适合稀疏图)

时间复杂度:树和图的模板 - 图3,适合正权稀疏图

const int N = 1e6+10;
typedef pair<int,int> PII;
// 稀疏图用邻接表存储
int h[N],w[N],e[N],ne[N],idx;
int dist[N]; // 距离起点的距离
bool st[N]; // 标记是否已更新为最短距离
int n,m;
// 加一条a指向b的边,权重为c
void add(int a,int b,int c){
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int dijkstra(){
    memset(dist,0x3f,sizeof dist);
    dist[1] = 0;
    priority_queue<PII,vector<PII>,greater<PII>> heap;
    heap.push({0,1}); // 第一关键字是距离,第二关键字是编号
    while(heap.size()){
        int distance = heap.top().first, id = heap.top().second;
        heap.pop();
        if(st[id]) continue; // 如果已经更新过了就跳过
        st[id] = true; 
        for(int i = h[id];i!=-1;i=ne[i]){
            int j = e[i];
            if(dist[j]>dist[id]+w[i]){
                dist[j] = dist[id]+w[i]; // 更新距离
                heap.push({dist[j],j}); 
            }
        }
    }
    if(dist[n]==0x3f3f3f3f) return -1;
    else return dist[n];
}
int main(){
    cin >> n >>m;
    // 初始化链表头
    memset(h,-1,sizeof h);
    while(m--){
        int a,b,c;
        cin >> a >> b >> c;
        add(a,b,c);
    }
    cout << dijkstra() << endl;
    return 0;
}

Bellman-ford算法(适合负权边)

Bellman-ford算法是求含负权图的单源最短路径的一种算法,效率较低,代码难度较小。其原理为连续进行松弛,在每次松弛时把每条边都更新一下,若在n-1次松弛后还能更新,则说明图中有负环,因此无法得出结果,否则就完成,时间复杂度:树和图的模板 - 图4
通俗的来讲就是:假设 1 号点到 n 号点是可达的,每一个点同时向指向的方向出发,更新相邻的点的最短距离,通过循环 n-1 次操作,若图中不存在负环,则 1 号点一定会到达 n 号点,若图中存在负环,则在 n-1 次松弛后一定还会更新。
Bellman-ford算法擅长解决有边数限制的最短路问题,下面的代码是求1号点到n号点的最多经过k条边的最短距离。

const int M = 1e4+100, N = 510;
struct Edge{
    int a,b,w;
}arr[M];
// backup为dist的备份数组,即上一次的数据,dist根据backup进行更新
int dist[N],backup[N];
int m,n,k;
int bellman_ford(){
    // 对距离数组初始化
    memset(dist,0x3f,sizeof dist);
    // 起点距自身的距离为0
    dist[1] = 0;
    // k条边的限制
    for(int i=0;i<k;i++){
        // backup保存的是dist的数据,然后在新的循环中,dist用过去的数据也就是backup进行更新
        memcpy(backup,dist,sizeof dist);
        for(int j=0;j<m;j++){
            auto e = arr[j];
            // 每次只松弛一条边
            dist[e.b] = min(dist[e.b],backup[e.a]+e.w);
        }
    }
    // 因为有负权边,所以不一定会是正无穷,可能会小一些
    if(dist[n]>0x3f3f3f3f/2) return -1;
    else return dist[n];
}
int main(){
    cin >> n >> m >> k;
    for(int i=0;i<m;i++){
        scanf("%d%d%d",&arr[i].a,&arr[i].b,&arr[i].w);
    }
    int t = bellman_ford();
    if(t==-1) puts("impossible");
    else cout << t << endl;
    return 0;
}

SPFA算法(适合有无负权边的图)

求最短路

时间复杂度:一般是树和图的模板 - 图5,最坏树和图的模板 - 图6
一般能用Dijkstra算法的也能用SPFA,如果被卡,则需要用堆优化本版的Dijkstra算法。

const int N = 1e5+100;
int e[N],ne[N],h[N],w[N],idx;
int dist[N];
// 标记是否在队列中
bool st[N]; 
int n,m;
// 添加一条从a指向b的权为c的边
void add(int a,int b,int c){
    e[idx]=b,ne[idx]= h[a], w[idx] = c, h[a] = idx++;
}
int spfa(){
    memset(dist,0x3f,sizeof dist);
    dist[1] = 0;
    // 将起点加入队列
    queue<int> q;
    q.push(1);
    st[1] = true;
    while(q.size()){
        int t = q.front(); q.pop();
        st[t] = false;
        // 遍历t的所有出边
        for(int i=h[t];i!=-1;i=ne[i]){
            int j = e[i];
            // 更新距离
            if(dist[j]>dist[t]+w[i]){
                dist[j]=dist[t]+w[i];
                // 如果该点不在队列中
                if(!st[j]){
                    q.push(j);
                    st[j] = true;
                }

            }
        }
    }
    if(dist[n]==0x3f3f3f3f) return -1;
    else return dist[n];
}
int main(){
    cin >> n >> m;
    memset(h,-1,sizeof h);
    for(int i=0;i<m;i++){
        int a,b,c;
        cin >> a >> b >> c;
        add(a,b,c);
    }
    int t = spfa();
    if(t==-1) puts("impossible");
    else cout << t << endl; 
    return 0;
}

判断负环

判断负环的基本思路是如果任意一点到当前点的距离是大于等于n的,由抽屉原理可得一定存在负环。这里dist表示任意一点到当前点的距离。
判断负环与求最短路不太一致:

  • dist这里不用初始化默认为0,因为负权边的存在,始终会进行最短距离的更新;
  • cnt表示任意一点到当前点最短距离对应的边数;
  • 最开始需要把所有节点加入队列,因为不能保证源点和负权环在同一个连通块中 ```cpp

    include

    include

    include

    include

using namespace std; const int N = 1e5+100; int e[N],ne[N],h[N],w[N],idx; // dist表示任意一点到当前点的距离,cnt表示任意一点到当前点最短距离对应的边数 int dist[N],cnt[N]; // 标记是否在队列中 bool st[N]; int n,m; // 添加一条从a指向b,权为c的边 void add(int a,int b,int c){ e[idx] = b,ne[idx]= h[a],w[idx]= c, h[a] = idx++; } bool spfa(){ // 这里区别于SPFA求最短路,这里不用初始化默认为0,因为负权边的存在,始终会进行最短距离的更新 // memset(dist,0x3f,sizeof dist); // dist[1] = 0; queue q; // 因为起点不一定是从1开始,如果把全部点都加到队列里面,肯定可以找到负环 for(int i=1;i<=n;i++) { q.push(i); st[i] = true; } while(q.size()){ // 弹出队头 int t = q.front(); q.pop(); st[t] = false; // 遍历所有出边 for(int i=h[t];i!=-1;i=ne[i]){ int j = e[i]; /// 更新距离 if(dist[j]>dist[t]+w[i]){ dist[j] = dist[t]+w[i]; cnt[j] = cnt[t]+1; // 如果距离起点的边不小于n,那肯定有负权环 if(cnt[j]>=n) return true; if(!st[j]){ q.push(j); st[j] = true; } } } } return false; } int main(){ cin >> n >> m; // 一定要初始化 memset(h,-1,sizeof h); while(m—){ int a,b,c; cin >> a >> b >> c; add(a,b,c); } if(spfa()) cout << “Yes” << endl; else cout << “No” << endl; return 0; }

<a name="qTh7p"></a>
## Floyd算法(求解多源最短路)
时间复杂度:![](https://cdn.nlark.com/yuque/__latex/4a7d22b39e93fbbcbe107e7a19e8bd34.svg#card=math&code=O%28n%5E3%29&height=23&width=43),可以求解多源最短路,可能含有负权的图等问题
```cpp
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;
const int N = 510, INF = 1e9+10;
int dist[N][N];
int n,m,Q;
void floyd(){
    for(int k=1;k<=n;k++){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]);
            }
        }
    }
}
int main(){
    cin >> n >> m >> Q;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            // 注意自环
            if(i==j) dist[i][j] = 0;
            else dist[i][j] = INF;
        }
    }
    while(m--){
        int a,b,c;
        cin >> a >> b >> c;
        // 避免重边
        dist[a][b] = min(dist[a][b],c);
    }    
    floyd();
    while(Q--){
        int a,b;
        cin >> a >> b;
        if(dist[a][b]>INF/2) puts("impossible");
        else cout << dist[a][b] << endl;
    }
    return 0;
}

最小生成树

树和图的模板 - 图7

朴素Prim算法

#include<bits/stdc++.h>
using namespace std;
const int N = 510,INF = 0x3f3f3f3f;
// 存储稠密图
int g[N][N];
// 存储当前点到集合的距离
int dist[N];
// 当前点是否在集合中
bool st[N];
int n,m;
int prim(){
    memset(dist,0x3f,sizeof dist);
    int res = 0;
    // 以1为起点
    dist[1] = 0; 
    for(int i=0;i<n;i++){
        int t = -1;
        // 从不在集合中的所有点中找到距离集合最近的
        for(int j=1;j<=n;j++){
            if(!st[j]&&(t==-1||dist[t]>dist[j])) t = j;
        }
        // 如果发现找到的这个点距离为正无穷,则直接返回
        if(dist[t]==INF) return INF;
        // 将这个点加入集合
        st[t] = true;
        res+= dist[t];
        // 更新集合外的点到集合的最短距离
        for(int j=1;j<=n;j++){
            if(!st[j]) dist[j] = min(dist[j],g[t][j]);
        }
    }
    return res;
}
int main(){
    cin >> n >> m;
    // 图一定要初始化
    memset(g,0x3f,sizeof g);
    while(m--){
        int a,b,c;
        cin >> a >> b >> c;
        // 重边和自环
        g[a][b] = g[b][a] = min(g[a][b],c);
    }
    int t = prim();
    if(t==INF) puts("impossible");
    else cout << t << endl;
    return 0;
}

Kruskal算法

按照边权排序,借助并查集判回路。

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+100;
struct Edge{
    int a,b,w;
}arr[N];
int p[N];
int n,m;
bool cmp(Edge a,Edge b){
    return a.w < b.w;
}
int find(int x){
    if(p[x]!=x) p[x] = find(p[x]);
    return p[x];
}
int main(){
    cin >> n >> m;
    for(int i=1;i<=m;i++){
        cin >> arr[i].a >> arr[i].b >> arr[i].w;
    }
    sort(arr+1,arr+m+1,cmp);
    for(int i=1;i<=n;i++) p[i] = i;
    int cnt = 0 , res = 0;
    for(int i=1;i<=m;i++){
        int fa = find(arr[i].a), fb = find(arr[i].b);
        if(fa==fb) continue;
        cnt ++;
        res += arr[i].w;
        p[fb] = fa;
    }
    if(cnt<n-1) puts("impossible");
    else cout << res << endl;
    return 0;
}

二分图

树和图的模板 - 图8一个图是二分图,当且仅当不含奇数环

染色法判定二分图

借助染色的思想来判定二分图,时间复杂度:树和图的模板 - 图9

#include<bits/stdc++.h>

using namespace std;
const int N = 1e5+100,M = 2*N;
int e[M],ne[M],h[N],idx;
int n,m;
// 记录每个点的颜色
int color[N];

void add(int a,int b){
    e[idx] = b , ne[idx] = h[a], h[a] = idx++;
}

bool dfs(int u,int c){
    color[u] = c;
    for(int i=h[u];i!=-1;i=ne[i]){
        int j = e[i];
        if(!color[j]){
            if(!dfs(j,3-c)) return false;
        }
        // 如果两个相邻点的染色是一样的,则出现矛盾
        else if(color[j]==c) return false;
    }
    return true;
}

int main(){
    cin >> n >> m;
    // 一定要初始化
    memset(h,-1,sizeof h);
    while(m--){
        int a,b;
        cin >> a >> b;
        // 无向图
        add(a,b), add(b,a);
    }
    bool flag = true;
    for(int i=1;i<=n;i++){
        if(!color[i]){
            if(!dfs(i,1)){
                flag = false; break;
            }
        }
    }
    if(flag) puts("Yes");
    else puts("No");
    return 0;
}

参考: