Luca25

Untitled

Aug 26th, 2018
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<pair<int, int> > g[1000001];
  6. long long int fil[1000001], dist[1000001], p[1000001], d1;
  7. int k;
  8.  
  9. void dfs(int h, int e, long long int d){
  10.     fil[h]=p[h];
  11.     if(p[h]==1) d1+=d;
  12.     for(int x=0; x<g[h].size(); x++){
  13.         if(g[h][x].first==e) continue;
  14.         dfs(g[h][x].first, h, d+g[h][x].second);
  15.         fil[h]+=fil[g[h][x].first];
  16.     }
  17. }
  18.  
  19. void f(int h, int e, long long int d){
  20.     for(int x=0; x<g[h].size(); x++){
  21.         if(g[h][x].first==e) continue;
  22.         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;
  23.         f(g[h][x].first, h, dist[g[h][x].first]);
  24.     }
  25. }
  26.  
  27. int trova_sede(int N, int K, int A[], int B[], int P[], int filiali[])
  28. {
  29.     k=K;
  30.     for(int x=0; x<K; x++) p[filiali[x]]=1;
  31.     for(int x=0; x<N-1; x++){
  32.         g[A[x]].push_back({B[x], P[x]});
  33.         g[B[x]].push_back({A[x], P[x]});
  34.     }
  35.     dfs(1, -1, 0);
  36.     dist[1]=d1;
  37.     f(1, -1, d1);
  38.     int pos=1;
  39.     for(int x=2; x<=N; x++) if(dist[x]<dist[pos]) pos=x;
  40.     return pos;
  41. }
Add Comment
Please, Sign In to add comment