1540B - Tree Array - CodeForces Solution


brute force combinatorics dp graphs math probabilities trees *2300

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define int long long

const int maxn = 209,modd = 1e9 + 7;
using namespace std;

int n,dep[maxn],fa[maxn][25],f[maxn][maxn];

vector<int> g[maxn];

int qp(int a,int b){
  int res = 1;
  while(b){
    if(b&1)res = (res*a)%modd;
    a = (a*a)%modd;
    b>>=1;
  }
  return res % modd;
}

void dfs(int u,int f){
  dep[u] = dep[f] + 1;
  fa[u][0] = f;
  for(int i = 1;i<=20;++i)
    fa[u][i] = fa[fa[u][i-1]][i-1];

  for(int v : g[u]){
    if(v!=f){
      dfs(v,u);
    }
  }
}

int lca(int x,int y){
  if(dep[x]>dep[y])swap(x,y);
  for(int i = 20;i>=0;i--)if(dep[fa[y][i]]>=dep[x])y = fa[y][i];
  if(x==y)return x;
  for(int i = 20;i>=0;i--)if(fa[x][i]!=fa[y][i])x = fa[x][i],y = fa[y][i];
  return fa[x][0];
}

signed main(){
  scanf("%lld",&n);
  for(int i = 1,u,v;i<n;++i){
    scanf("%lld%lld",&u,&v);
    g[u].push_back(v),g[v].push_back(u);
  }

  int inv2 = qp(2,modd-2);
  for(int i = 1;i<=n;++i)f[0][i] = 1;
  for(int i = 1;i<=n;++i){
    for(int j = 1;j<=n;++j){
      f[i][j] = (f[i-1][j] + f[i][j-1])*inv2%modd;
    }
  }

  int ans = 0;
  for(int i = 1;i<=n;++i){
    dfs(i,0);
    for(int j = 1;j<=n;++j){
      for(int k = 1;k<j;++k){
	int _lca = lca(j,k);
	ans = (ans + f[dep[j] - dep[_lca]][dep[k] - dep[_lca]])%modd;
      }
    }
  }

  printf("%lld",ans*qp(n,modd-2)%modd);
}


Comments

Submit
0 Comments
More Questions

519B - A and B and Compilation Errors
1152B - Neko Performs Cat Furrier Transform
1411A - In-game Chat
119A - Epic Game
703A - Mishka and Game
1504C - Balance the Bits
988A - Diverse Team
1312B - Bogosort
1616B - Mirror in the String
1660C - Get an Even String
489B - BerSU Ball
977C - Less or Equal
1505C - Fibonacci Words
1660A - Vasya and Coins
1660E - Matrix and Shifts
1293B - JOE is on TV
1584A - Mathematical Addition
1660B - Vlad and Candies
1472C - Long Jumps
1293D - Aroma's Search
918A - Eleven
1237A - Balanced Rating Changes
1616A - Integer Diversity
1627B - Not Sitting
1663C - Pōja Verdon
1497A - Meximization
1633B - Minority
688B - Lovely Palindromes
66B - Petya and Countryside
1557B - Moamen and k-subarrays