poj3268 Dijkstra算法 边既有权又有花费

48 篇文章 0 订阅
9 篇文章 0 订阅

题意: 

        给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。

代码:

#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
#define INF 1e9
const int maxn = 1000+10;
int n,m;
 
struct Edge
{
    int from,to,dist,cost;
    Edge(int f,int t,int d,int c):from(f),to(t),dist(d),cost(c){}
};
 
struct HeapNode
{
    int d,c,u;
    HeapNode(int d,int c,int u):d(d),c(c),u(u){}
    bool operator<(const HeapNode&rhs)const
    {
        return d>rhs.d || (d==rhs.d && c>rhs.c);
    }
};
 
struct Dijkstra
{
   int n,m;
   vector<Edge> edges;
   vector<int> G[maxn];
   bool done[maxn];
   int d[maxn];
   int c[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,int cost)
   {
       edges.push_back(Edge(from,to,dist,cost));
       m = edges.size();
       G[from].push_back(m-1);
   }
 
   void dijkstra(int s)
   {
       priority_queue<HeapNode> Q;
       for(int i=0;i<n;i++) d[i]=INF,c[i]=INF;
       d[s]=c[s]=0;
       Q.push(HeapNode(d[s],c[s],s));
       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&&c[e.to]>c[u]+e.cost)  )
               {
                   d[e.to]= d[u]+e.dist;
                   c[e.to]= c[u]+e.cost;
                   Q.push(HeapNode(d[e.to],c[e.to],e.to));
               }
           }
       }
   }
}DJ;
 
int main()
{
    while(scanf("%d%d",&n,&m)==2&&n)
    {
        DJ.init(n);
        for(int i=0;i<m;i++)
        {
            int u,v,d,c;
            scanf("%d%d%d%d",&u,&v,&d,&c);
            u--,v--;
            DJ.AddEdge(u,v,d,c);
            DJ.AddEdge(v,u,d,c);
        }
        int s,e;
        scanf("%d%d",&s,&e);
        s--,e--;
        DJ.dijkstra(s);
        printf("%d %d\n",DJ.d[e],DJ.c[e]);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值