Tuesday, August 6, 2019

0/1 BFS | Competitive Programming


Basics:

Problems:
(3)   Topcoder SRM-436 Div-1, 500 (Topcoder).
(4)   Vjudge: 1.
(5)   A2OJ.
/// 0_1-BFS.cpp
/// (Data Structure: graph, cost, visit, deque)
vector<int> g[100001],cost[100001];
int dist[100001]; /// initially= INT_MAX
bool vis[100001];
int bfs01(int s, int n)
{
    for(int i=0;i<n+1;i++)
    dist[i]=INT_MAX, vis[i]=0;
    deque<int>q;
    q.push_front(s);
    dist[s]=0;
    while(!q.empty())
    {
        int u= q.front();
        q.pop_front();
        if(vis[u]) continue;
        vis[u]=true;
        for(int i=0;i<g[u].size();i++)
        {
            int v=g[u][i];
            if(dist[u]+cost[u][i]<=dist[v])
            {
                dist[v]=dist[u]+cost[u][i];
                if(cost[u][i]==0)
                    q.push_front(v);
                else q.push_back(v);
            }
        }
    }
    return dist[n-1];
}

No comments:

Post a Comment