Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<pair<int, int> > g[1000001];
- long long int fil[1000001], dist[1000001], p[1000001], d1;
- int k;
- void dfs(int h, int e, long long int d){
- fil[h]=p[h];
- if(p[h]==1) d1+=d;
- for(int x=0; x<g[h].size(); x++){
- if(g[h][x].first==e) continue;
- dfs(g[h][x].first, h, d+g[h][x].second);
- fil[h]+=fil[g[h][x].first];
- }
- }
- void f(int h, int e, long long int d){
- for(int x=0; x<g[h].size(); x++){
- if(g[h][x].first==e) continue;
- dist[g[h][x].first]=d-g[h][x].second*fil[g[h][x].first]+(k-fil[g[h][x].first])*g[h][x].second;
- f(g[h][x].first, h, dist[g[h][x].first]);
- }
- }
- int trova_sede(int N, int K, int A[], int B[], int P[], int filiali[])
- {
- k=K;
- for(int x=0; x<K; x++) p[filiali[x]]=1;
- for(int x=0; x<N-1; x++){
- g[A[x]].push_back({B[x], P[x]});
- g[B[x]].push_back({A[x], P[x]});
- }
- dfs(1, -1, 0);
- dist[1]=d1;
- f(1, -1, d1);
- int pos=1;
- for(int x=2; x<=N; x++) if(dist[x]<dist[pos]) pos=x;
- return pos;
- }
Add Comment
Please, Sign In to add comment