dijkstra+堆优化 USACO 3.2.6 Sweet Butter

本文介绍了一种结合Dijkstra算法与堆优化的方法,并通过USACO 3.2.6 SweetButter题目进行实践演示。文章详细解释了各数组的作用及如何利用堆优化算法提高效率。

想练一练dijkstra+堆优化,从来没有写过~

要看懂以下内容 首先自学 dijkstra 算法, 和 堆哦~


一开始考虑是想堆里存结构体,但是经过潘神指导,发现不需要~毕竟写结构体会蛋疼些。。


介绍一下各个数组的作用

d[i] 表示 从源点 s 到 节点 i 的当前最短距离

v[i] 其实和 d[i] 是一个东西,也是源点 s 到 节点 i 的当前最短距离, 唯一的不同是 当一个节点 i 已经被确认为最短路径的点 后,  v[i] = inf, 这样在下次取堆的最小元素的时候,就不会取到已经拓展完毕的点。

简单来说 就是 堆的维护 用 v[i] 而不是 d[i], 而最终答案存在 d[i] 里。


heap[i] 表示 堆里的 第 i 个 元素 是 实际的 哪个节点。(堆到图中点的映射)

pos[i] 表示 实际的节点 i 是堆里的哪个元素 (图中点到堆的映射)


end, first, cost, next 都是基本的邻接表的数组。(比较喜欢用数组而不是指针~)


这样的话 思路就比较清晰了,代码不长,也很容易懂。

这里我用 USACO 3.2.6 Sweet Butter 作为例题,实现 dijstra+堆优化(其实这题用 SPFA 很容易过。。)  


/*
PROG:butter
LANG:C++
*/

#include <cstdio>
#include <algorithm>

using namespace std;

const int inf = ~0U>>1;
const int MAXN = 1000, MAXM = 3000;
int end[MAXM], first[MAXN], cost[MAXM], next[MAXM];
int d[MAXN], v[MAXN], heap[MAXN], pos[MAXN], cow[501];
int n, p, c, tot, ans=inf, dist[501][MAXN];

void ins(int x, int y, int z)
{
    end[++tot] = y, cost[tot] = z;
    next[tot] = first[x], first[x] = tot;
}

void Swap(int i, int j)
{
    swap(pos[heap[i]], pos[heap[j]]);   // 将 图中点 映射到 堆中的位置 交换
    swap(heap[i], heap[j]);             // 将 堆中元素 映射到的 图中点 交换
}

void pushUp(int x)  // 向上维护
{
    for ( ;x != 1 && v[heap[x]] < v[heap[x>>1]];x >>= 1)
    Swap(x, x>>1);
}

void pushDown(int x) // 向下维护
{
    for (x += x; x <= p; x += x)
    {
        if (x+1 <= p && v[heap[x]] > v[heap[x+1]]) ++x;
        if (v[heap[x>>1]] > v[heap[x]]) Swap(x, x>>1);
    }
}

void update(int x, int value) // 更新节点距离,注意是使用 v[i]
{
    v[x] = value;
    pushUp(pos[x]);
    pushDown(pos[x]);
}

void dijkstra(int s)
{
    for (int i = 1;i <= p;++i)
    {
        heap[i] = pos[i] = i;              // 初始化映射
        d[i] = v[i] = inf;                 // 初始化距离
    }
    d[s] = 0;
    update(s, 0);
    for (int i = 0;i < p;++i)
    {
        int tmp = heap[1];
        for (int k = first[tmp]; k ; k = next[k])
        {
            if (cost[k]+d[tmp] < d[end[k]])
            {
                d[end[k]] = cost[k]+d[tmp];
                update(end[k], d[end[k]]);
            }
        }
        update(tmp, inf);              // 拓展完后,将该节点在堆中的值改为 inf 
    }
}

int main()
{
    freopen("butter.in", "r", stdin);
    freopen("butter.out", "w", stdout);
    int x, y, z;
    scanf("%d%d%d", &n, &p, &c);
    for (int i = 1;i <= n;++i) scanf("%d", &cow[i]);
    for (int i = 1;i <= c;++i)
    {
        scanf("%d%d%d", &x, &y, &z);
        ins(x, y, z);
        ins(y, x, z);
    }
    for (int i = 1;i <= n;++i)
    {
        dijkstra(cow[i]);
        for (int j = 1;j <= p;++j) dist[i][j] = d[j];
    }
    for (int i = 1;i <= p;++i)
    {
        int tmp = 0;
        for (int j = 1;j <= n;++j) tmp += dist[j][i];
        if (tmp < ans) ans = tmp;
    }
    printf("%d\n", ans);
}




### 使用优化Dijkstra算法C++中的实现 Dijkstra算法的核心在于逐步扩展当前已知的最短路径,而为了提高效率,可以利用优先队列(最小)来加速选取下一个待处理的节点的过程。以下是基于优化Dijkstra算法C++中的具体实现。 #### 1. 算法概述 传统的Dijkstra算法通过线性扫描的方式寻找距离起点最近的未访问节点,时间复杂度为 \(O(V^2)\),其中 \(V\) 是图中顶点的数量。当使用二叉作为优先队列时,可以在 \(O(\log V)\) 的时间内完成插入和删除操作,从而将总的时间复杂度降低至 \(O((E+V)\log V)\)[^2],其中 \(E\) 表示图中边的数量。 #### 2. C++ 实现代码 下面是一个完整的优化Dijkstra 算法C++ 实现: ```cpp #include <iostream> #include <vector> #include <queue> #include <climits> using namespace std; struct Edge { int to; long long weight; }; // 定义一个小根比较函数 struct Compare { bool operator()(const pair<long long, int>& a, const pair<long long, int>& b) { return a.first > b.first; // 按照距离从小到大排列 } }; void dijkstra(int start, vector<vector<Edge>>& adjList, vector<long long>& dist) { priority_queue<pair<long long, int>, vector<pair<long long, int>>, Compare> pq; // 初始化距离数组 for (int i = 0; i < dist.size(); ++i) { dist[i] = LLONG_MAX; } dist[start] = 0; pq.push({0, start}); while (!pq.empty()) { auto current = pq.top(); pq.pop(); int u = current.second; long long d = current.first; // 如果已经找到了更优的距离,则跳过此节点 if (d > dist[u]) continue; // 遍历相邻节点并尝试更新距离 for (auto& edge : adjList[u]) { int v = edge.to; long long w = edge.weight; if (dist[v] > dist[u] + w) { // 松弛操作 dist[v] = dist[u] + w; pq.push({dist[v], v}); } } } } int main() { int n, m, s; cin >> n >> m >> s; // 输入节点数、边数以及起点编号 vector<vector<Edge>> adjList(n + 1); // 邻接表表示图 for (int i = 0; i < m; ++i) { int from, to, weight; cin >> from >> to >> weight; adjList[from].push_back(Edge{to, weight}); // 单向边 } vector<long long> dist(n + 1); dijkstra(s, adjList, dist); // 输出结果 for (int i = 1; i <= n; ++i) { cout << "Distance from source to node " << i << ": "; if (dist[i] == LLONG_MAX) { cout << "INF\n"; // 若不可达则输出 INF } else { cout << dist[i] << "\n"; } } return 0; } ``` #### 3. 关键点析 - **数据结构的选择** 使用 `priority_queue` 和自定义比较器实现了最小的功能,能够快速获取当前距离起点最近的节点[^4]。 - **松弛操作** 当发现一条新的路径使得目标节点的距离变得更小时,立即更新其距离值,并将其加入优先队列以便后续进一步探索[^3]。 - **性能提升** 利用优化后的版本显著减少了不必要的重复计算,在稀疏图上的表现尤为突出。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值