Question: DE Shaw, Online Assessment Test (IIIT Bhopal | SDET | FTE) | Smallest Sorted Array | Connected Graph | 15th August 2023
5
Entering edit mode

ADD COMMENTlink 12 months ago Delta 2.8k
2
Entering edit mode

Approach:

We can solve this problem using dfs .As we want 1 to have the last value as g_nodes and value of all other nodes as 0,we will start our dfs from 1. When we  have traversed all the adjacent nodes of a particular node ,we return its current value to its parent where it will be added to value of parent. And as we have processed all the nodes and come out after traversing adjacent nodes of 1,we return to our main function.

//CODE:

#include <bits/stdc++.h>

using namespace std;

#define f(n, i, x) for (int i = x; i < n; i++)

#define vb push_back

#define ll long long

vector<vector<int>> list1;

vector<int> vis;

vector<int> level;

int ans = 0;

int dfs(int cur, int k)

{

    if (!vis[cur])

    {

        vis[cur] = 1;

        for (auto x : list1[cur])

        {

            level[cur] += dfs(x, k);

        }

        if (cur == 1)

            return 0;

        ans += ceil((1.0 * level[cur]) / k);

        return level[cur];

    }

    else

        return 0;

}

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int n, k;

    cin >> n >> k;

    list1.resize(n + 1);

    level.resize(n + 1, 1);

    vis.resize(n + 1, 0);

    int a[n];

    f(n - 1, i, 0) cin >> a[i];

    (n + 1);

    f(n - 1, i, 0)

    {

        int x;

        cin >> x;

        list1[a[i]].vb(x);

        list1[x].vb(a[i]);

    }

    int z = dfs(1, k);

    cout << ans << endl;

}

ADD COMMENTlink 11 weeks ago Arpan • 70
0
Entering edit mode


 

ADD COMMENTlink 11 weeks ago Parth Dhokane • 0

Login before adding your answer.

Similar Posts
Loading Similar Posts