HDU 3790 最短路径问题

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

题意 : 经典的求最短路问题。表示上午刚刚学了点并查集后,因为有场最短路的练习,就突击学习了下最短路,表示很伤的学了刘汝佳的算法竞赛书上的代码,再加上肉鸽学长的教导,终于写出了我的ACM生涯中的第一个最短路(orz...)


典型的Dijkstra算法,用dis和cos两个数组分别保存距离和花费...


//Danceonly

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int INF = 100000007;
const int maxn = 1005;
#define MIN(a,b) (a > b ? b : a)
#define MAX(a,b) (a > b ? a : b)
struct node
{
      int d,p;
}q[maxn][maxn];
int vis[maxn],dis[maxn],cos[maxn];
int N,M;
int main()
{
      while (scanf("%d%d",&N,&M) == 2 && (N || M))
      {
            for (int i=1;i<=N;i++)
                  for (int j=1;j<=N;j++)
                  q[i][j].d = q[i][j].p = INF;
            for (int i=1;i<=M;i++)
            {
                  int a,b,d,p;
                  scanf("%d%d%d%d",&a,&b,&d,&p);
                  if (q[a][b].d > d || (q[a][b].d == d && q[a][b].p > p))
                  {
                        q[a][b].d = d;
                        q[a][b].p = p;
                  }
                  q[b][a] = q[a][b];
            }
            int startx,endx;
            scanf("%d%d",&startx,&endx);
            memset(vis,0,sizeof(vis));
            //vis[startx] = 1;
            for (int i=1;i<=N;i++)
            {
                  dis[i] = (i == startx ? 0 : INF);
                  cos[i] = dis[i];
            }
            for (int i=1;i<=N;i++)
            {
                  int x,m = INF,n = INF;
                  for (int y=1;y<=N;y++)
                        if (vis[y] == 0)
                              if (dis[y] < m || (dis[y] == m && cos[y] < n))
                              {
                                    x = y;
                                    m = dis[x];
                                    n = cos[x];
                              }
                  vis[x] = 1;
                  for (int y=1;y<=N;y++)
                  {
                        if (dis[y] > dis[x] + q[x][y].d){dis[y] = dis[x] + q[x][y].d;cos[y] = cos[x] + q[x][y].p;}
                        else if (dis[y] == dis[x] + q[x][y].d && cos[y] > cos[x] + q[x][y].p)
                        {
                              dis[y] = dis[x] + q[x][y].d;
                              cos[y] = cos[x] + q[x][y].p;
                        }
                        else ;
                  }

            }
            printf("%d %d\n",dis[endx],cos[endx]);
      }
      return 0;
}
/*
3 3
1 2 5 6
2 3 4 5
1 3 4 5
1 3


*/

转载于:https://www.cnblogs.com/cnwsycf/p/3335372.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值