1843D - Apple Tree - CodeForces Solution


combinatorics dfs and similar dp trees

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void dfs(ll node, vector<int> adj[], vector<bool> &vis, vector<ll> &leaf)
{
  vis[node] = true;
  if (adj[node].size() == 1 && node != 1)
    leaf[node] = 1;

  for (auto &nei : adj[node])
  {
    if (!vis[nei])
    {
      dfs(nei, adj, vis, leaf);
      leaf[node] += leaf[nei];
    }
  }
}

int main()
{
  int t;
  cin >> t;
  while (t--)
  {
    int n;
    cin >> n;
    vector<int> adj[n + 1];
    for (int i = 0; i < n - 1; i++)
    {
      int a, b;
      cin >> a >> b;
      adj[a].push_back(b);
      adj[b].push_back(a);
    }
    vector<bool> vis(n + 1, false);
    vector<ll> leaf(n + 1, 0);

    dfs(1, adj, vis, leaf);

    int q;
    cin >> q;
    for (int i = 0; i < q; i++)
    {
      int x, y;
      cin >> x >> y;
      cout << leaf[x] * leaf[y] * 1LL << endl;
    }
  }
  return 0;
}


Comments

Submit
0 Comments
More Questions

1525D - Armchairs
1257A - Two Rival Students
1415A - Prison Break
1271A - Suits
259B - Little Elephant and Magic Square
1389A - LCM Problem
778A - String Game
1382A - Common Subsequence
1512D - Corrupted Array
667B - Coat of Anticubism
284B - Cows and Poker Game
1666D - Deletive Editing
1433D - Districts Connection
2B - The least round way
1324A - Yet Another Tetris Problem
246B - Increase and Decrease
22E - Scheme
1566A - Median Maximization
1278A - Shuffle Hashing
1666F - Fancy Stack
1354A - Alarm Clock
1543B - Customising the Track
1337A - Ichihime and Triangle
1366A - Shovels and Swords
919A - Supermarket
630C - Lucky Numbers
1208B - Uniqueness
1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set