zoukankan      html  css  js  c++  java
  • HDU 2066 最短路floyd算法+优化

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

    题意 从任意一个邻居家出发 到达任意一个终点的 最小距离

    解析 求多源最短路 我想到的是Floyd算法 但是题目给出的n的大小不确定 所以图很稀疏 会有很多孤立点 会多跑很多没用的路径 需要优化一下 不然会超时

      我看其他人很多都是用迪杰斯特拉写的,可以试试

    AC代码

     1 #include <stdio.h>
     2 #include <math.h>
     3 #include <string.h>
     4 #include <stdlib.h>
     5 #include <iostream>
     6 #include <sstream>
     7 #include <algorithm>
     8 #include <string>
     9 #include <queue>
    10 #include <ctime>
    11 #include <vector>
    12 using namespace std;
    13 const int maxn= 1e3+5;
    14 const int maxm= 1e8+5;
    15 const int inf = 0x3f3f3f3f;
    16 typedef long long ll;
    17 int dp[maxn][maxn],a[maxn][maxn];
    18 int n,m,t,l[maxn],q[maxn];
    19 int main()
    20 {
    21     while(scanf("%d %d %d",&n,&m,&t)!=EOF)
    22     {
    23         for(int i=1;i<=maxn;i++)
    24             for(int j=1;j<=maxn;j++)    //初始化长度
    25             {
    26                 if(i==j)
    27                     dp[i][j]=0;
    28                 else
    29                     dp[i][j]=inf;
    30             }
    31          int x,y,d;
    32          int maxx=0;
    33          for(int i=0;i<n;i++)
    34          {
    35              scanf("%d %d %d",&x,&y,&d);
    36              maxx=max(maxx,max(x,y));
    37              if(dp[x][y]>d)
    38                 dp[x][y]=dp[y][x]=d;        //有平行边 更新为最小的边权
    39          }
    40          for(int i=0;i<m;i++)
    41             scanf("%d",&l[i]);
    42          for(int i=0;i<t;i++)
    43             scanf("%d",&q[i]);
    44          for(int k=1;k<=maxx;k++)          //三个 for Floyd板子
    45             for(int i=1;i<=maxx;i++)
    46                 if(dp[i][k]!=inf)           //优化一下 如果边为inf直接跳过第三个for
    47                 for(int j=1;j<=maxx;j++)
    48                         dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]);
    49          int ans=inf;
    50          for(int i=0;i<m;i++)              //枚举起点和终点组成的路径 找最小值
    51             for(int j=0;j<t;j++)
    52                 ans=min(ans,dp[l[i]][q[j]]);
    53         printf("%d
    ",ans);
    54     }
    55     return 0;
    56 }
  • 相关阅读:
    按回车键提交表单
    Access数据库类型及属性
    Problem 1002
    问题 1003
    Problem 1003
    Switch Game(摘自LP学C++)
    1006
    膜拜蛇形矩阵
    A == B?
    Rectangles
  • 原文地址:https://www.cnblogs.com/stranger-/p/7810938.html
Copyright © 2011-2022 走看看