dfs and similar greedy math trees *1800

Please click on ads to support us..

C++ Code:

/*বিসমিল্লাহির রাহমানির রাহীম*/
#include<bits/stdc++.h>
using namespace std;
#define int long long

const int N = 1e5 + 5;

int n, m;
int people[N];
int h[N];
vector<int> g[N];
int vis[N];
int totalvis[N];
int totalgood[N];

bool ok = true;

void dfs1(int s) {
  totalvis[s] = people[s];
  vis[s] = 1;
  int sum = 0;
  for(int child : g[s]) {
    if(vis[child] == 0) {
      dfs1(child);
      totalvis[s] += totalvis[child];
      sum += totalgood[child];
    }
  }
  int x = h[s] + totalvis[s];
  if(x % 2 == 0) {}
  else ok = false;
  totalgood[s] = x / 2;
  if(totalgood[s] >= 0 and totalgood[s] <= totalvis[s]) {}
  else ok = false;
  if(sum <= totalgood[s]) {}
  else  ok = false;
}

void solve() {
  cin >> n >> m;
  people[n + 1];
  ok = true;
  for(int i = 1; i <= n; i++) {
    cin >> people[i];
  }
  for(int i = 1; i <= n; i++) {
    cin >> h[i];
  }
  for(int i = 1; i < n; i++) {
    int u, v; cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs1(1);
  if(ok) {
    cout << "YES" << endl;
  }
  else {
    cout << "NO" << endl;
  }
  for(int i = 1; i <= n; i++) {
    g[i].clear();
    vis[i] = 0;
  }
}

int32_t main() {

  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

  int t = 1;
  cin >> t;
  while(t--) {
    solve();
  }
}


Comments

Submit
0 Comments
More Questions

515C - Drazil and Factorial
1151E - Number of Components
1151F - Sonya and Informatics
556A - Case of the Zeros and Ones
867A - Between the Offices
1569A - Balanced Substring
260A - Adding Digits
1698C - 3SUM Closure
1029B - Creating the Contest
1421A - XORwice
1029A - Many Equal Substrings
1675D - Vertical Paths
1271C - Shawarma Tent
805A - Fake NP
1163A - Eating Soup
787A - The Monster
807A - Is it rated
1096A - Find Divisible
1430C - Numbers on Whiteboard
1697B - Promo
208D - Prizes Prizes more Prizes
659A - Round House
1492C - Maximum width
171B - Star
1512B - Almost Rectangle
831B - Keyboard Layouts
814A - An abandoned sentiment from past
268C - Beautiful Sets of Points
1391C - Cyclic Permutations
11A - Increasing Sequence