AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

图论复习【增强手感】

作者: 作者的头像   浩然正气 ,  2023-03-19 22:11:27 ,  所有人可见 ,  阅读 40


1


2

Dijstra最短路算法

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 500010;

typedef pair<int, int> PII;

#define x first
#define y second

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

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

int dijstra()
{
    //  初始化距离
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    //  定义一个小根堆
    priority_queue<PII, vector<PII>, greater<PII>> q;
    q.push({0, 1});

    while (!q.empty())
    {
        auto t = q.top();
        q.pop();
        int id = t.y, d = t.x;
        if (st[id] == true)
            continue;
        st[id] = true;

        for (int i = h[id]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > d + w[i])
            {
                dist[j] = d + w[i];
                q.push({ dist[j], j });
            }
        }
    }

    if (dist[n] == 0x3f3f3f3f)
        return -1;
    return dist[n];
}

int main()
{
    int a, b, c;
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);

    while (m -- )
    {
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    printf("%d\n", dijstra());
    return 0;
}

bellman_ford算法

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 500010;
const int INF = 0x3f3f3f3f;

int n, m, k;
int dist[N];
int copys[N];

struct Edge
{
    int a, b, w;
}edge[N];

int bellman_ford()
{
    /**初始化距离**/
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    for (int i = 0; i < k; i ++ )
    {
        memcpy(copys, dist, sizeof dist);
        for (int j = 0; j < m; j ++ )
        {
            int a = edge[j].a;
            int b = edge[j].b;
            int w = edge[j].w;
            dist[b] = min(dist[b], copys[a] + w);
        }
    }

    if (dist[n] > INF / 2)
        return -1;
    return dist[n];
}

int main()
{
    int a, b, w;
    scanf("%d%d%d", &n, &m, &k);

    for (int i = 0; i < m; i ++ )
    {
        scanf("%d%d%d", &a, &b, &w);
        edge[i] = {a, b, w};
    }

    int res = bellman_ford();
    if ((res == -1) && (dist[n] != -1))
        puts("impossible");
    else
        printf("%d\n", res);
    return 0;
}

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息