zoukankan      html  css  js  c++  java
  • k短路

    k短路dijkstra(堆优化)

    首先A*算法主要思想是
    估价函数
    进而夹带一个BFS的思想
    对所有边进行松弛
    进而对每个点进行改变
    最后加一个特判
    以防RE;
    k短路的模版题
    直接上代码
    有一点小小的读入优化不懂的话可以直接用scanf

    #include<bits/stdc++.h>
    using namespace std;
    const int INF=0x7fffffff;
    const int M=50005;
    int m,n,k,p,ans[M],cnt;
    int d[M];
    bool vis[M];
    int read()
    { int x=0,f=1;char ch=getchar();
      while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
      while (ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
      return x*f;
    }
    struct edge
    { int to,dist;}; vector<edge> g[M],lg[M]; 
    struct node
    { int pos;
      int dis;
      bool operator<(const node & x) const 
      { return x.dis<dis;
      }
    };
    struct headnode
    { int pos;
      int g;
      int step;
      bool operator<(const headnode & x) const 
      { return (x.g==g)?x.step<step:x.g<g;
      }
    };
    priority_queue<node> que;
    priority_queue<headnode> q;
    void dijkstra(int s)
    { for (int i=1;i<=n;i++) d[i]=INF;
      d[s]=0;que.push((node){s,0});
      while (!que.empty())
      { node tmp=que.top();que.pop();
        int x=tmp.pos;
        if (vis[x]) continue;
        vis[x]=true;
        for (int i=0;i<lg[x].size();i++)
        { int y=lg[x][i].to,dd=lg[x][i].dist;
          if (d[y]>d[x]+dd) 
          { d[y]=d[x]+dd;
           if (!vis[y]) {que.push((node){y,d[y]});}
         }
        }
      }
    }
    int shrt[M];
    void A_star(int s)
    { memset(ans,-1,sizeof(ans));
      headnode zz,mm;
      zz.g=0;zz.pos=s;zz.step=0;
      q.push(zz);
      while (!q.empty()) 
      { mm=q.top();q.pop();
        int x=mm.pos;
        shrt[x]++;
        if (shrt[x]>k) continue;
        if (x==1)
        { cnt++;
          ans[cnt]=mm.step;
          continue;
        }
        for (int i=0;i<g[x].size();i++)
        { int y=g[x][i].to,dd=g[x][i].dist;
          zz.pos=y;zz.step=mm.step+dd;zz.g=zz.step+d[y];
          q.push(zz);
        }
      }
    }
    int main()
    { n=read();m=read();k=read();
      for (int i=1;i<=m;i++)
      { int x,y,z;
        x=read();y=read();z=read();
        g[x].push_back((edge){y,z});
        lg[y].push_back((edge){x,z});
      }
      dijkstra(1);
      A_star(n);
      for (int i=1;i<=k;i++)
      printf("%d
    ",ans[i]);
      return 0;
    }
    慢即是快,细则是能,于小处铸迤逦
  • 相关阅读:
    AMap公交线路查询
    AMap行政区查询服务
    使用JavaScript的Join方法
    获取layer.open弹出层的返回值
    MVC项目中WebViewPage的实战应用
    ASP.NET管道
    Android接收系统广播
    python字符串转换成数字
    mysql缓存
    两个矩阵对应位置的数据相加,并返回一个矩阵
  • 原文地址:https://www.cnblogs.com/Hale522520/p/10186231.html
Copyright © 2011-2022 走看看