HDU 2680 Choose the best route(简单Dijkstra)

本文介绍了解决HDU2680问题的方法,通过添加超级源点或反转图来简化问题,利用Dijkstra算法高效地求解多起点到单终点的最短路径。

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

HDU 2680 Choose the best route(简单Dijkstra)

http://acm.hdu.edu.cn/showproblem.php?pid=2680

题意:

        一个有向图求最短路径.不过起点有很多个,终点只有一个.

分析:

        添加一个超级源点,该点到其他普通起点的距离为0.只需要求该超级源到终点的距离即可.

        也可以将原图反向,然后求终点到所有起点的最短距离,然后求最小值即可.

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define INF 1e9
using namespace std;
const int maxn=1000+10;
int n,m,end_point;
vector<int> st;//起点集合

struct Edge
{
    int from,to,dist;
    Edge(int f,int t,int d):from(f),to(t),dist(d){}
};

struct HeapNode
{
    int d,u;
    HeapNode(int d,int u):d(d),u(u){}
    bool operator<(const HeapNode&rhs)const
    {
        return d>rhs.d;
    }
};

struct Dijkstra
{
    int n,m;
    vector<Edge> edges;
    vector<int> G[maxn];
    bool done[maxn];
    int d[maxn];

    void init(int n)
    {
        this->n=n;
        for(int i=0;i<n;i++) G[i].clear();
        edges.clear();
    }

    void AddEdge(int from,int to,int dist)
    {
        edges.push_back(Edge(from,to,dist));
        m = edges.size();
        G[from].push_back(m-1);
    }

    int dijkstra()
    {
        priority_queue<HeapNode> Q;
        for(int i=0;i<n;i++) d[i]=INF;
        d[0]=0;
        Q.push(HeapNode(d[0],0));
        memset(done,0,sizeof(done));

        while(!Q.empty())
        {
            HeapNode x=Q.top(); Q.pop();
            int u = x.u;
            if(done[u]) continue;
            done[u]=true;

            for(int i=0;i<G[u].size();i++)
            {
                Edge &e=edges[G[u][i]];
                if(d[e.to] > d[u]+e.dist)
                {
                    d[e.to]=d[u]+e.dist;
                    Q.push(HeapNode(d[e.to],e.to));
                }
            }
        }
        if(d[end_point]==INF) return -1;
        return d[end_point];
    }
}DJ;

int main()
{
    while(scanf("%d%d%d",&n,&m,&end_point)==3)
    {
        DJ.init(n+1);   //n+1是因为我们多加了0号点:超级源
        for(int i=0;i<m;i++)
        {
            int u,v,d;
            scanf("%d%d%d",&u,&v,&d);
            u,v;
            DJ.AddEdge(u,v,d);
        }
        int w;
        scanf("%d",&w);
        while(w--)
        {
            int u;
            scanf("%d",&u);
            DJ.AddEdge(0,u,0);
        }
        printf("%d\n",DJ.dijkstra());
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值