zoukankan      html  css  js  c++  java
  • 线性数组维护图+队列bfs分层

    一共两个知识点:

    1、通过线性数组维护有向/无向图

    2、通过队列维护分层的bfs遍历

    原题链接-K 站中转内最便宜的航班

    //线性表存储图 + 队列实现的分层bfs算法
    
    class Solution {
    public:
        class stu{
        public://当前节点的配对节点、下一个节点的cnt编号、线路权值
            int vertex,next,value;
            stu(){};
            stu(int a,int b,int c):vertex(a),next(b),value(c){};
        };
        
        //两个数组+一个编号变量维护一张图
        stu mapper[4000];
        int cnt;
        int head[101];
        
        //用来添加一条路径u->v且权值为w
        void add(int u,int v,int w)
        {
            mapper[cnt] = stu(v,head[u],w);
            head[u] = cnt++;
        }
    
        //注意初始化特点
        void init(int n)
        {
            cnt = 0;
            memset(head,-1,sizeof(head));
        }
    
        //将题目给出的vector信息用一维数组维护
        void TransToMapper(vector<vector<int> >& flights,int n)
        {
            init(n);//初始化
            for(vector<int>& rhs : flights) add(rhs[0],rhs[1],rhs[2]);
        }
    
        //描述队列中当前节点的状态的变量
        class statu{
        public://当前节点、截止到当前节点的积累权值和
            int vertex,sum;
            statu(int a,int b):vertex(a),sum(b){};
        };
    
        //解决问题的函数
        int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K)
        {
            //转换成为线性地图
            TransToMapper(flights,n);
            //bfs层次遍历
            queue<statu> que;
            que.push(statu(src,0));
            int step = 0;
            int ans = 0x3f3f3f3f;
            while(!que.empty() && step<= K)
            {
                //对于每一个层次而言
                //用长度描述其在队列中的所在位置
                int lenth = que.size();
                //然后每一层次对应每一次循环
                while(lenth--)
                {
                    statu psd = que.front();
                    que.pop();
                    int u = psd.vertex;
                    int cursum = psd.sum;
                    //注意下面如何使用一维数组维护下的图
                    for(int i=head[u];~i;i=mapper[i].next)
                    {
                        int v = mapper[i].vertex;
                        int nextsum = mapper[i].value + cursum;
                        if(nextsum >= ans)continue;
                        else if(v == dst)ans = min(ans,nextsum);
                        else que.push(statu(v,nextsum));
                    }
                }
                //一个层次访问完毕就step+1
                step++;
            }
            return ans == 0x3f3f3f3f ? -1 : ans ;
        }
    };
    

    OK

  • 相关阅读:
    Linux脚本中使用特定JDK
    redis 模糊匹配批量清理 keys
    git push 本地项目推送到远程分支
    extentreports报告插件之extentX之服务搭建(三)
    extentreports报告插件与testng集成(二)
    extentreports报告插件与testng集成(一)
    初识ios自动化(一)
    css 选择器
    appium移动端测试之滑动(二)
    使用appium进行ios测试,启动inspector时遇到的问题(一)
  • 原文地址:https://www.cnblogs.com/savennist/p/13598149.html
Copyright © 2011-2022 走看看