博客
关于我
POJ 2387 Til the Cows Come Home(Dijkstra优先队列)
阅读量:332 次
发布时间:2019-03-04

本文共 1915 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要找到Bessie从最后一个标志N走回第一个标志1的最短路径。这个问题可以通过使用Dijkstra算法来解决,因为道路是权重比较大的,且没有负权边。

方法思路

  • 问题分析:这是一个典型的最短路径问题,适合使用Dijkstra算法来解决。我们需要找到从节点N到节点1的最短路径。
  • 数据结构:使用邻接矩阵来表示道路连接,每个道路的权重即为道路的长度。
  • 算法选择:使用优先队列来实现Dijkstra算法,优先处理距离较小的节点,确保找到最短路径。
  • 优化:每次从优先队列中取出距离最小的节点,更新其邻居的最短距离,并将邻居加入队列。
  • 解决代码

    #include 
    #include
    #include
    #include
    using namespace std;struct node { int d; int pos;};bool operator<(const node& a, const node& b) { return a.d < b.d;}int main() { while (true) { int m, n; scanf("%d %d", &m, &n); if (scanf("%d %d", &m, &n) == EOF) break; int INF = 2005; int e[2005][2005]; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { e[i][j] = (i == j) ? INF : 0; } } for (int i = 1; i <= m; ++i) { int u, v, w; scanf("%d %d %d", &u, &v, &w); if (e[u][v] > w) { e[u][v] = w; e[v][u] = w; } } int dis[n + 1]; int book[n + 1]; fill(dis.begin(), dis + n + 1, INF); fill(book.begin(), book + n + 1, 0); dis[n] = 0; priority_queue
    q; q.push({0, n}); while (!q.empty()) { node t = q.top(); q.pop(); if (t.pos == 1) break; if (book[t.pos] == 1) continue; book[t.pos] = 1; for (int j = 1; j <= n; ++j) { if (book[j] == 0 && dis[j] > dis[t.pos] + e[t.pos][j]) { dis[j] = dis[t.pos] + e[t.pos][j]; q.push({dis[j], j}); } } } cout << dis[1] << endl; }}

    代码解释

  • 输入处理:读取输入数据,包括道路的数量T和标志的数量N,然后读取每条道路的信息,填充邻接矩阵。
  • 初始化:设置邻接矩阵中所有距离为无穷大,除了起点N的距离为0。
  • 优先队列:使用优先队列来处理节点,优先处理距离较小的节点。
  • Dijkstra算法:每次取出距离最小的节点,更新其邻居的最短距离,并将邻居加入队列,直到找到目标节点1。
  • 输出结果:输出从节点N到节点1的最短距离。
  • 转载地址:http://lpnh.baihongyu.com/

    你可能感兴趣的文章
    PS辅助工具Assistor PS
    查看>>
    pt-archiver 归档历史数据及参数详解
    查看>>
    pt-online-schema-change使用详解
    查看>>
    PyTorch 模型性能分析和优化 — 第 2 部分
    查看>>
    PTA L1-011 A-B
    查看>>
    pta l2-1紧急救援(Dijkstra)
    查看>>
    pta求阶乘序列前n项和_学霸整理——求数列的通项公式解法集锦,转化、归纳一文全懂...
    查看>>
    SpringBoot中集成Redis实现对redis中数据的解析和存储
    查看>>
    pthread_create导致的程序崩溃
    查看>>
    ptyhon POSIX
    查看>>
    public private protected default小结
    查看>>
    PublicCMS怎么用金蝶Apusic Application Server部署
    查看>>
    publish over ssh、 Kubernetes Continuous Deploy插件
    查看>>
    PubMed详解-ChatGPT4o作答
    查看>>
    Pubsub Extensions for Smack
    查看>>
    pulsar mq 单体验证demo, docker启动pulsar mq验证生产者消费者命令
    查看>>
    pulsar mq 学习使用,pulsar java客户端, spring boot pulsar , spring pulsarTemplate如何使用 pulsar4.0.0
    查看>>
    Pulsar mq 设置延迟消息模式 pulsar mq 发送延迟消息 pulsar如何发送消费延时消息
    查看>>
    Pulsar 游标回滚,移动偏移量测试
    查看>>
    pulsar开源消息队列_了解Pulsar---Pulsar工作笔记001
    查看>>