poj3159 candies dijkstra

本文介绍了一种使用优先队列优化的Dijkstra算法实现,并通过添加vis数组进行剪枝操作,提高了查找最短路径的效率。该算法适用于解决图论中的最短路径问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. dijkstra 算法,利用优先队列优化,找到最近的点。
  2. 添加vis数组剪枝。
  3. 优先队列重载运算符时,右边的值优先级大放在前,所以 a > b表示从小到大排列。

题目链接:http://acm.hust.edu.cn/vjudge/problem/17126

#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;

#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;

const double PI = 3.141592653589;
const int INF = 0x3fffffff;

struct Edge{
    int to, cost;
    Edge(int nto, int ncost) : to(nto),cost(ncost){}
    Edge(){};
    bool operator < (const Edge& rhs) const{
        return cost > rhs.cost;
    }
};

vector<vector<Edge> > G;
priority_queue<Edge> pq;
int d[30010], n;


int dijkstra(int head, int tail){
    while(!pq.empty())
        pq.pop();
    fill(d+1, d+n+1, INF);
    pq.push(Edge(head, 0));
    d[head] = 0;

    Edge t;
    while(!pq.empty()){
        t = pq.top();  pq.pop();
        if(t.to == tail)
            break;
        if(d[t.to] < t.cost)
            continue;
        for(int i = 0; i < G[t.to].size(); ++i){
            Edge e = G[t.to][i];
            if(d[e.to] > t.cost + e.cost) {
                d[e.to] = t.cost + e.cost;
                pq.push(Edge(e.to, d[e.to]));
            }
        }
    }
    return t.cost;
}

int main(){
//        freopen("/Users/really/Documents/code/input","r",stdin);
    //    freopen("/home/really/Document/output","w",stdout);
    //    ios::sync_with_stdio(false);


    int a,b,c, m;
    scanf("%d%d",&n,&m);
    G.resize(n+5);
    for(int i = 0; i < m; ++i){
        scanf("%d%d%d", &a, &b, &c);
        G[a].push_back(Edge(b,c));
    }

    int ans = dijkstra(1,n);
    printf("%d\n",ans);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值