图论相关的算法代码模板

1、Dijkstra求最短路 朴素版

稠密图,邻接矩阵存储,找单源最短路,首先起点设置为dist = 0,其他点均为正无穷

每次从已经可到达并且还没有确定最短路的里面选一个最短的,从这个点拓展出去看看能不能更新其他点为更短的路径,这个点也就确定了到达的最短路

遍历n - 1次之后,就是从所有的点遍历过一次,所有的点也就被确定好了最短的距离

代码如下:
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 510;

int n, m;
int g[N][N];
int dist[N];
int st[N];

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    
    for(int i = 0; i < n - 1; i ++)
    {
        //从还没有确定最短距离的里面,找一个到当前点距离最短的
        int t = -1;
        for(int j = 1; j <= n; j ++)
            //还没确定最短路 && (没找到比当前点最短的 || 这个点的距离更短比我记录的最短的点还短)  更新t为当前点
            if(!st[j] && (t == -1 || dist[t] > dist[j]))
                t = j;
        
        for(int j = 1; j <= n; j ++)
            dist[j] = min(dist[j], dist[t] + g[t][j]);
        
        st[t] = true;
    }
    
    if(dist[n] == 0x3f3f3f3f) return -1;
    
    return dist[n];
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(g, 0x3f, sizeof g);
    
    for(int i = 0; i < m; i ++){
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        g[a][b] = min(g[a][b], c);
    }
    
    printf("%d\n", dijkstra());
    
    return 0;
}

2、Dijkstra求最短路 堆优化版

思路还是跟上面的一样,把最消耗时间的部分(从所有可达并且没有确定最短路径的点里找最小的)用堆(STL优先队列)来存储

稀疏图,邻接表来存储

优先队列的初始化操作:

priority_queue<T,Sequence,Compare>

T:存放容器的元素类型

Sequence:实现优先级队列的底层容器,默认是vector<T>

Compare:用于实现优先级的比较函数,默认是functional中的less<T>

这样就是每次取出来top 也就是距离最小值,然后从这个点出去拓展一圈,每次拓展到的点也就有距离了

Note:代码中 PII 的first 是到这个点的距离 second 是这个点

代码如下:
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010, M = 2 * N;
typedef pair<int, int> PII;

int n, m;
int h[N], w[M], e[M], ne[M], idx;
int st[N];
int dist[N];

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())
    {
        auto f = heap.top();
        heap.pop();
        
        int ver = f.second, distance = f.first;
        
        if(st[ver]) continue;
        
        for(int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(dist[j] > distance + w[i])
            {
                dist[j] = distance + w[i];
                heap.push({dist[j], j});
            }
        }
        
        st[ver] = true;
    }
    
    if(dist[n] == 0x3f3f3f3f)   return -1;
    return dist[n];
    
    
}

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

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;
}

3、bellman-ford求最短路,带负权边

求走K条边能到达的点的最短路

首先,遍历K次,每次都要去枚举所有的边,更新从A到B的距离和原来到B的距离,留下是最小的那一个

这里要存一个backup数组,每次判断A到B的距离和B原来的距离的时候,要用BackUp里的来找,因为有可能会链式的传导过去

比如:1 - 2 - 3
本来2 和 3初始化之后都是正无穷,遍历1 - 2的时候,把2更新了,然后再遍历2 - 3的时候又把3给更新了, 但是实际上的结果,1 - 3是没有边的,这一轮的遍历结束之后3还应该保持正无穷 或者是1 - 3 的权值

代码如下:
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

int n, m, k;
const int N = 510, M = 10010;

int dist[N], backup[N];

struct edge{
    int a, b, w;
}edges[M];

void bellman_ford()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    
    for(int i = 0; i < k; i ++)
    {
        memcpy(backup, dist, sizeof dist);
        for(int j = 0; j < m; j ++)
        {
            int a = edges[j].a, b = edges[j].b, w = edges[j].w;
            dist[b] = min(dist[b], backup[a] + w);
        }
    }
    
}

int main()
{
    scanf("%d%d%d", &n, &m, &k);
    
    for(int i = 0; i < m; i ++)
    {
        int a, b, w;
        scanf("%d%d%d", &a, &b, &w);
        edges[i] = {a, b, w};
    }
    
    bellman_ford();
    
    if(dist[n] > 0x3f3f3f3f / 2)    puts("impossible");
    else printf("%d", dist[n]);
    
    return 0;
}
4、SPFA算法:改进bellman-ford 求最短路 带负权边(最坏o(n * m))

bellman-ford算法中的每一次遍历所有的边太慢了,改用每次只更改可能会产生变动的边

只有当一个点他前面节点的路径长度变短了之后,他才有可能会变成更短的一个路径长度,那么就开一个队列,每次修改之后,如果这个节点还没有在队列中,就让他入队

每次取出队头元素,遍历这个节点的所有出边,去看看是否有更短路的选择

代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

int n, m;
const int N = 100010;
int dist[N];
int h[N], w[N], e[N], ne[N], idx;
bool st[N];

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;
        
        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;
                }
            }
        }
    }
    
    return dist[n];
}

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

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    
    for(int i = 0; i < m; i ++)
    {
        int a, b, w;
        scanf("%d%d%d", &a, &b, &w);
        add(a, b, w);
    }
    
    int t = spfa();
    
    if (t == 0x3f3f3f3f) puts("impossible");
    else printf("%d\n", t);
    
    return 0;
    
}
4.2 SPFA算法:改进bellman-ford 判定有无负环 带负权边(最坏o(n * m))

在上面的基础上稍加改进,抽屉原理

记录一个走到每个点最少要走的路径数,如果路径数量超过n了,就说明一定至少有一个点走了两次,那么肯定是这么走能让权值减少,也就是存在负环

关于初始化的时候要把所有的点都加入到队列中,是因为有可能从1号点是走不进去负环的

代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

int n, m;
const int N = 10010;
int cnt[N], dist[N];
int h[N], w[N], e[N], ne[N], idx;
bool st[N];


int spfa()
{
    queue<int> q;
    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;
                
                if(cnt[j] >= n) return true;
                if(!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }
    
    return false;
}

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

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    
    for(int i = 0; i < m; i ++)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    
    if(spfa())  puts("Yes");
    else    puts("No");
    
    return 0;
}
5、Floyd:多源最短路
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int n, m, k;
const int N = 210, INF = 1e9;
int g[N][N];

void floyd()
{
    for(int k = 1; k <= n; k ++)
        for(int i = 0; i <= n; i ++)
            for(int j = 0; j <= n; j ++)
                g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
}

int main()
{
    scanf("%d%d%d", &n, &m, &k);
    
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            if(i == j)  g[i][j] = 0;
            else    g[i][j] = INF;
    
    for(int i = 0; i < m; i ++)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        g[a][b] = min(g[a][b], c);
    }
    
    floyd();
    
    while(k --)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        if(g[a][b] > INF / 2)   puts("impossible");
        else printf("%d\n", g[a][b]);
    }
    
    return 0;
}
6、Prim算法求最小生成树(稠密图)

首先把所有位置初始化成INF

每次去枚举所有的点,找一个离得最近的,并且是还没有被划到最小生成树范围里面的点,把他划到这个最小生成树里

之后再用这个点去更新一下所有其他的点,这里的范围不是和迪杰斯特拉一样求到第一个点的距离,而是到已经划分的这个最小生成树的距离

代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

int n, m;
int g[N][N], dist[N];
bool st[N];

int prim()
{
    int res = 0;
    memset(dist, 0x3f, sizeof dist);
    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(i && dist[t] == INF) return INF;
        if(i)   res += dist[t];
        
        for(int j = 1; j <= n; j ++)    dist[j] = min(dist[j], g[t][j]);
        st[t] = true;
    }
    
    return res;
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(g, 0x3f, sizeof g);
    
    while(m --)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        g[a][b] = g[b][a] = min(g[a][b], c);
    }
    
    int t = prim();
    
    if(t == INF)    puts("impossible");
    else    printf("%d\n", t);
    
    return 0;
}
7、Kruskal算法求最小生成树(稀疏图)

1、所有边按权重从小到大排序
2、应用并查集,每次枚举到边之后,先看a 和 b是否联通,如果不连通,那么就把这个边加进去,也就是把a 和 b这两个集合给联通到一起

代码如下:
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 200010;
int n, m;
int p[N];

struct Edge{
    int a, b, w;
    bool operator< (const Edge &W) const
    {
        return w < W.w;
    }
}edges[N];

int find(int x)
{
    if(p[x] != x)   p[x] = find(p[x]);
    return p[x];
}

int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 0; i < m; i ++)
        scanf("%d%d%d", &edges[i].a, &edges[i].b, &edges[i].w);
    
    sort(edges, edges + m);
    
    for(int i = 1; i <= n; i ++)    p[i] = i;
    
    int res = 0, cnt = 0;
    for(int i = 0; i < m; i ++)
    {
        int a = edges[i].a, b = edges[i].b, w = edges[i].w;
        a = find(a), b = find(b);
        if(a != b)
        {
            p[a] = b;
            res += w;
            cnt ++;
        }
    }
    
    if(cnt < n - 1) puts("impossible");
    else    printf("%d\n", res);
    
    return 0;
}

8、染色法判定二分图:

二分图就是白的跟黑的连,黑的跟白的连,不能俩颜色一样的连在一起

从一个点开始深度优先遍历,每次如果这个点没有标记颜色,就给他标记一下继续搜
如果标记过颜色了,并且和将要标记的颜色出现了矛盾,那么就返回FALSE
知道搜完所有点,返回true

代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 100010, M = N * 2;
int h[N], e[M], ne[M], idx;
int color[N];
int n, m;

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()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    
    while(m --)
    {
        int a, b;
        scanf("%d%d", &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;
    
}
9、匈牙利算法:

给定一个二分图,问最大匹配
一个匹配定义为:两个元素之间只有一条边,没有同时连着两条边的情况

首先左边的先遍历他所有的边,每次先去占住一个,然后再发生冲突的时候,就看看已经连接的左边的这个元素,还能不能换个其他元素连,如果能就换一下皆大欢喜,如果不能就false

代码如下:
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 510, M = 100010;
int n1, n2, m;
int h[N], e[M], ne[M], idx;
bool st[N];
int match[N];

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

bool find(int x)
{
    for(int i = h[x]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(!st[j])
        {
            st[j] = true;
            if(match[j] == 0 || find(match[j]))
            {
                match[j] = x;
                return true;
            }
        }
    }
    
    return false;
}

int main()
{
    scanf("%d%d%d", &n1, &n2, &m);
    memset(h, -1, sizeof h);
    
    while(m --)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        add(a, b);
    }
    
    int res = 0;
    for(int i = 1; i <= n1; i ++)
    {
        memset(st, false, sizeof st);
        if(find(i)) res ++;
    }
    
    printf("%d\n", res);
    
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值