Advertisement
111-111-111

Min cost random navigation O(n^2)

Apr 10th, 2020
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. vector<vector<int>> adj;
  7. // costs array
  8. vector<double> C;
  9. vector<double> dp;
  10.  
  11. //pV is parent of node V
  12. void dfs(int V, int pV){
  13.    
  14.     //traverse over all children
  15.     double sum=0;
  16.     double count=0;
  17.     for(auto son: adj[V]){
  18.         if(son == pV) continue;
  19.         dfs(son, V);
  20.         sum+=dp[son];
  21.         count++;
  22.        
  23.     }
  24.     if(count>0)
  25.         sum/=count;
  26.     sum+=C[V];
  27.     dp[V]=sum;
  28. }
  29.  
  30. int main() {
  31.     ios_base::sync_with_stdio(false);
  32.     int n;
  33.     cin>>n;
  34.     adj=vector<vector<int>> (n);
  35.     C=vector<double> (n,0.0);
  36.    
  37.     for(int  i=0;i<n-1;i++){
  38.         int x,y;
  39.         cin>>x>>y;
  40.         adj[x].push_back(y);
  41.         adj[y].push_back(x);
  42.     }
  43.     for(int  i=0;i<n;i++){
  44.         double cost_Vi;
  45.         cin>>cost_Vi;
  46.         C[i]=cost_Vi;
  47.     }
  48.  
  49.     int v_strat_best=0;
  50.     double min_cost=100000000;
  51.     for(int i=0;i<n;i++)
  52.     {
  53.         dp=vector<double> (n,0.0);
  54.         dfs(i,-1);
  55.         if(dp[i]<min_cost)
  56.         {
  57.             v_strat_best=i;
  58.             min_cost=dp[i];
  59.         }
  60.     }
  61.     cout << v_strat_best <<" "<< min_cost;
  62.    
  63.  
  64. }
  65. /*
  66.  input:
  67.  4
  68. 0 1
  69. 1 2
  70. 1 3
  71. 1
  72. 1
  73. 1
  74. 100
  75.  
  76. output:
  77. 1 35
  78. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement