【问题标题】:Special case in shortest path algorithm最短路径算法的特殊情况
【发布时间】:2018-12-03 08:13:07
【问题描述】:

我给出了一个带有V 顶点、E 边、一个源顶点s 和一个数字m 的图
每条边的权重等于one
我必须找到与源节点的距离小于给定数字m的所有节点的最短路径@

我的方法:- 我使用 Dijkstra 算法并为所有节点找到路径 然后选择那些距离小于m但我得到时间的节点 超出限制。

有没有更好的方法或任何人可以建议的算法?

更新:-

我使用了 BFS,但在某些情况下,我仍然得到 TLE,我试图不跨越所有节点,而不仅仅是那些距离源 s 小于 m 的节点,并将它们存储在 temp
如果我的方法有误,请纠正我。

这是我的代码

    #include <bits/stdc++.h>

    using namespace std;

    const long long N = 5*1e4;
    const long long W = 1e9;
    const long long INF = 1e9;
    vector<long long> g[N];                //graph 
    long long dist[N];                     //distance
    bool visited[N];                       // is node visited or  not
    void shortest_path(long long s,long long m){
            fill(dist, dist + N, INF);
            fill(visited, visited + N, 0);
            dist[s] = 0;
            vector<int>temp;    
            queue<long long>q;              //Queue
            q.push(s);
            while(!q.empty())
                {
                    long long v = q.front();
                    q.pop();
                    if(visited[v]) continue;
                    visited[v] = 1;
                    temp.push_back(v);       //storing nodes in temp
                    for(auto it: g[v])
                    {
                        long long u = it;
                        if(dist[v] + 1<= m)  // nodes those distance is less than m
                        {
                            dist[u] = dist[v] + 1;
                            q.push(u);
                        }
                    }
                }
               for(int i=0;i<temp.size();i++){
                        cout<<temp[i]<<" ";
                  }
    }
int main()
{
        long long n;
        cin>>n;
        for(long long i = 0; i < n; ++i) g[i].clear();
        for(long long i = 0; i < n-1; i++)
        {
            long long u,v;
            cin>>u>>v;
            u--;v--;
            g[u].push_back(v);
            g[v].push_back(u);
        }
        long long q;
        cin>>q;
        for(long long i=0;i<q;i++){
            long long s,m;
            cin>>s>>m;
            s--;
            shortest_path(s,m);
             cout<<endl;
        }
    return 0;
}

【问题讨论】:

  • 每条边的权重等于1 -> 使用bfs,而不是dijstra

标签: algorithm dijkstra shortest-path


【解决方案1】:

Dijkstra 只是 BFS,由于优先级队列,它适用于加权图,但如果您的图未加权,您可以只使用 BFS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多