This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <string.h>
#include <iterator>
#include <list>
#include <cmath>
#include <math.h>
#include <unordered_map>
#include <numeric>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pi;
vector<int> adj[1000001]; // change
ll people[1000001]; // change
multiset<ll> sums[1000001]; // change
ll subtree[1000001]; // change
void dfsSubtree(ll node, ll parent, ll parentSum) {
// sums[node].insert(parentSum); // record the cumulative sum from root
subtree[node] += people[node];
for (auto u: adj[node]) {
if (u != parent) { // traverse to the next node, adding on the parentSum
// the subtree sum of the next node must be returned and added
dfsSubtree(u, node, parentSum + people[node]);
subtree[node] += subtree[u]; // subtree u is the sum for the child
sums[node].insert(subtree[u]);
}
}
}
void dfsParents(ll node, ll parent, ll parentSum) {
sums[node].insert(parentSum);
for (auto u : adj[node]) {
if (u != parent) {
ll res = subtree[0]-subtree[u];
// cout << "going from: "<< node << " to " << u << ", parentsum: " << res << endl;
// must send parentSum = entire tree sum - dest node subtree
dfsParents(u, node, res);
// subtree[node] += subtree[u]; // subtree u is the sum for the child
// sums[node].insert(subtree[u]);
}
}
}
int LocateCentre(int N,int P[],int S[], int D[]) {
for (int i = 0; i <N-1; i ++) {
adj[S[i]].push_back(D[i]);
adj[D[i]].push_back(S[i]);
}
for (int i = 0; i < N; i ++) {
people[i] = P[i];
}
// for (auto i : people) {
// cout << i << " ";
// }
// cout << endl;
// for (auto item : adj) {
// for (auto i : item) {
// cout << i << " ";
// }
// cout << endl;
// }
dfsSubtree(0, -1, 0);
// for (auto item : subtree) {
// cout << item << " " << endl;
// }
// cout << "now for all sums" << endl;
dfsParents(0, -1, 0);
// for (auto item : sums) {
// for (auto i : item) {
// cout << i << " ";
// }
// cout << endl;
// }
ll minRoad = 1E12;
ll city = -1;
for (int i = 0; i < N; i++) {
if (*sums[i].rbegin() < minRoad) {
minRoad = *sums[i].rbegin();
city = i;
}
}
return city;
}
// int main() {
// int P[5] = {10,10,10,20,20};
// int S[4] = {1, 2, 2, 3};
// int D[4] = {2, 0, 3, 4};
// cout << LocateCentre(5, P, S, D);
// }
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |