Wealth Disparity, INOI 2016
Problem Description​
Question : Wealth Disparity, INOI 2016
Submit Code : Codechef
Prerequisites​
Solution​
Problem ask us to find maximum value of difference that a node and its ancestor can have.
To find this we will follow steps:
- We will make tree out of provided parent/manager array.
- Apply DFS to find minimum wealth of sub-nodes of node
iand store it in arrayminWealth[i]. - Take maximum of
wealth[i] - minWealth[i]to find maximum wealth disparity.
Code​
#include<bits/stdc++.h>
using namespace std;
void findMinWealth(vector<int>* adj, vector<int>& wealth, vector<int>& minWealth, int manager){
int childMinWealth = wealth[manager];
for(int u : adj[manager]){
findMinWealth(adj, wealth, minWealth, u);
childMinWealth = min(childMinWealth, minWealth[u]);
}
minWealth[manager] = childMinWealth;
}
int main(){
int n;
cin >> n;
vector<int> wealth(n+1);
int manager, hojo;
vector<int> adj[n+1];
for(int i=1;i<=n;i++)
cin >> wealth[i];
for(int i=1;i<=n;i++){
cin >> manager;
if(manager != -1)
adj[manager].push_back(i);
else
hojo = i;
}
vector<int> minWealth(n+1);
findMinWealth(adj, wealth, minWealth, hojo);
int ans = 0;
for(int i=1;i<=n;i++)
ans = max(ans, wealth[i] - minWealth[i]);
cout << ans;
return 0;
}