Hacker Rank Breadth First Search: Shortest Reach


#include<bits/stdc++.h>

using namespace std;

#define fast ios_base::sync_with_stdio(0)
#define bfast cin.tie(0)
#define outs(x) cout << x << " "
#define outn(x) cout << x << "\n"
#define sf scanf
#define pf printf
#define pfn(x , k) printf(k , x)
#define nl puts("")
#define psb push_back
#define mset(c,v) memset(c , v , sizeof c)
#define loop0(n) for(int i=0; i<n; i++)
#define loop1(n) for(int i=1; i<=n; i++)
#define mpair(x , y) make_pair(x , y)
#define all(x) x.begin(), x.end()
#define pi acos(-1.0)
#define psb push_back
#define clr clear()

typedef unsigned long long ull;
typedef long long LL;
typedef vector<int>vii;
typedef vector<LL>vll;
typedef vector<string>vs;
typedef map<int, int>mpii;
typedef map<string, int>mpsi;
typedef map<char, int>mpci;
typedef map<LL, LL>mpll;

const int mod = 1000007;
const int high = 1e3+5;

vii adj[high];
int visited[high] , cost[high];

void cln()
{
    for(int i=0; i<high; i++)
    {
        adj[i].clr;
        visited[i] = 0;
        cost[i] = 0;
    }
}

void BFS(int s)
{
    cost[s] = 0;

    visited[s] = 1;

    queue<int>Q;
    Q.push(s);

    while(!Q.empty())
    {
        int u = Q.front();

        Q.pop();

        for(int i=0; i<adj[u].size(); i++)
        {
            int v = adj[u][i];

            if(!visited[v])
            {
                visited[v] = 1;
                cost[v] = cost[u] + 6;
                Q.push(v);
            }
        }
    }
}

int main()
{
    fast;
    int test;
    cin >> test;
    while(test--)
    {
        cln();

        int i , n , m;
        cin >> n >> m;

        for(i=0; i<m; i++)
        {
            int u , v;
            cin >> u >> v;

            adj[u].psb(v);
            adj[v].psb(u);
        }

        int start=0;
        cin >> start;

        BFS(start);

        for(i=1; i<=n; i++)
        {
            if(i == start) continue;

            if(!cost[i]) cout << "-1 ";
            else cout << cost[i] << " ";
        }

        cout << "\n";
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number