zoukankan      html  css  js  c++  java
  • HDU 3790 (Djikstra)

    题目链接如下:

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

    这题用最短路径Djikstra就可以解决,用Floyd会超时!

    代码如下:

    #include <iostream>
    using namespace std;

    const int INF = 999999999;
    const int N = 1001;
    struct
    {
      int distance;
      int price;
    } map[N][N];
    int dist[N];
    int price[N];
    int visited[N];

    void djikstra(int s, int t, int n);

    int main()
    {
      int n, m;
      int i, j, a, b, d, p;
      int s, t;
      while(scanf("%d%d", &n, &m) != EOF && (n || m))
      {
        for(i = 1; i <= n; i++)
        {
          for(j = 1; j <= n; j++)
          {
            map[i][j].distance = INF;
            map[i][j].price = INF;
          }
        }
        for(i = 1; i <= n; i++)
        {
          map[i][i].distance = 0;
          map[i][i].price = 0;
        }
        for(i = 1; i <= m; i++)
        {
          scanf("%d%d%d%d", &a, &b, &d, &p);
          if(map[a][b].distance > d)
           {
            map[a][b].distance = map[b][a].distance = d;
            map[a][b].price = map[b][a].price = p;
          }
        }
        scanf("%d%d", &s, &t);
        djikstra(s, t, n);
      }
      return 0;
    }

    void djikstra(int s, int t, int n)
    {
      int i, j;
      int min, k;
      memset(visited, 0, sizeof(visited));
      for(i = 1; i <= n; i++)
      {
        dist[i] = map[s][i].distance;
        price[i] = map[s][i].price;
      }
      visited[s] = 1;
      for(i = 1; i <= n; i++)
      {
        min = INF;
        for(j = 1; j <= n; j++)
        {
          if(!visited[j] && dist[j] < min)
          {
            min = dist[j];
            k = j;
          }
        }
        if(min == INF)
        {
          break;
        }
        visited[k] = 1;
        for(j = 1; j <= n; j++)
        {
          if(!visited[j])
          {
            if(dist[j] > dist[k] + map[k][j].distance)
            {
              dist[j] = dist[k] + map[k][j].distance;
              price[j] = price[k] + map[k][j].price;
            }
            else if(dist[j] == dist[k] + map[k][j].distance)
            {
              if(price[j] > price[k] + map[k][j].price)
              {
                price[j] = price[k] + map[k][j].price;
              }
            }
          }
        }
      }
      printf("%d %d\n", dist[t], price[t]);
    }

  • 相关阅读:
    经常使用的两个清爽的table样式
    wdcp新开站点或绑定域名打不开或无法访问的问题
    在线客服代码,可以用
    $smarty获取变量get,post等用法
    mysql 替换某个字段中的某个字符
    git 设置不需要输入密码
    linux批量查找文件内容
    使用PHP QR Code生成二维码
    RabbitMQ-2
    RabbitMQ-1
  • 原文地址:https://www.cnblogs.com/10jschen/p/2620334.html
Copyright © 2011-2022 走看看