#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N = 200000+1;
vector<int> tree[N];
int n, k;

int parent[N];
void dfs1(int node){
       for(auto i : tree[node])
              if(parent[i]==0){
                     parent[i] = node;
                     dfs1(i);
              }
}

ll Ps[N];
ll cnt[N][5];
void dfs2(int node){
       for(auto i : tree[node])
              if(parent[i]==node){
                     dfs2(i);
                     Ps[node] += Ps[i] + cnt[i][0];
                     for(int j = 0; j < k; j++)
                            cnt[node][j] += cnt[i][(j+k-1)%k];
              }
       cnt[node][0]++;
}

ll Pd[N];
ll ST[N][5];
ll ans;
void dfs3(int node){
       if(node == 1){
              ST[node][0]++;
              for(auto i : tree[node])
                     dfs3(i);
              return;
       }
       Pd[node] = Pd[parent[node]] + ST[parent[node]][0];
       ans += Pd[node];
       for(int i = 0; i < k; i++)
              ST[node][i] += ST[parent[node]][(i+k-1)%k];
       for(int i = 0; i < k; i++)
              ST[parent[node]][i] += cnt[node][(i+k-1)%k];
       Pd[parent[node]] += Ps[node] + cnt[node][0];
       ST[node][0]++;
       for(auto i : tree[node])
              if(parent[i]==node)
                     dfs3(i);
}

void solve(){
       cin >> n >> k;
       int a, b;
       for(int i = 0; i < n-1; i++){
              cin >> a >> b;
              tree[a].push_back(b);
              tree[b].push_back(a);
       }
       parent[1] = 1;
       dfs1(1);
       dfs2(1);
       ans = 0;
       dfs3(1);
       cout << ans;
}

int main(){
       ios::sync_with_stdio(false);

       solve();

       return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N = 200000;
vector<int> tree[N];
int n, k;

int parent[N];
void dfs1(int node){
       for(auto i : tree[node])
              if(parent[i]==0){
                     parent[i] = node;
                     dfs1(i);
              }
}

ll Ps[N];
ll cnt[N][5];
void dfs2(int node){
       for(auto i : tree[node])
              if(parent[i]==node){
                     dfs2(i);
                     Ps[node] += Ps[i] + cnt[i][0];
                     for(int j = 0; j < k; j++)
                            cnt[node][j] += cnt[i][(j+k-1)%k];
              }
       cnt[node][0]++;
}

ll Pd[N];
ll ST[N][5];
ll ans;
void dfs3(int node){
       if(node == 1){
              ST[node][0]++;
              for(auto i : tree[node])
                     dfs3(i);
              return;
       }
       Pd[node] = Pd[parent[node]] + ST[parent[node]][0];
       ans += Pd[node];
       for(int i = 0; i < k; i++)
              ST[node][i] += ST[parent[node]][(i+k-1)%k];
       for(int i = 0; i < k; i++)
              ST[parent[node]][i] += cnt[node][(i+k-1)%k];
       Pd[parent[node]] += Ps[node] + cnt[node][0];
       ST[node][0]++;
       for(auto i : tree[node])
              if(parent[i]==node)
                     dfs3(i);
}

void solve(){
       cin >> n >> k;
       int a, b;
       for(int i = 0; i < n-1; i++){
              cin >> a >> b;
              tree[a].push_back(b);
              tree[b].push_back(a);
       }
       parent[1] = 1;
       dfs1(1);
       dfs2(1);
       ans = 0;
       dfs3(1);
       cout << ans;
}

int main(){
       ios::sync_with_stdio(false);

       solve();

       return 0;
}


#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using vi = vector<int>;
int n,k;
ll res;

const int MAX = 2e5+10;
ll s[MAX][5];
ll q[MAX][5];
vi e[MAX];
int v[MAX];

void dfs(int x){
	v[x] = 1;
	q[x][0] += 1;
	for(int y: e[x]){
		if( v[y] ) continue;
		dfs(y);
		for(int i=0;i<k;i++){
			for(int j=0;j<k;j++){
				res += s[x][i]*q[y][j];
				res += s[y][j]*q[x][i];
				int c1 = (i + j +1)/k;
				if( (i+j+1)%k) c1 ++;
				int c2 = i/k + j/k;
				if( i%k) c2++;
				if( j%k ) c2++;
				res += q[x][i]*q[y][j]*(c1-c2);
			}
		}
		for(int i=0;i<k;i++){
			q[x][(i+1)%k] += q[y][i];
			s[x][(i+1)%k] += s[y][i];
		}
		s[x][1] += q[y][0];
	}
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n >> k;
	for(int i=0;i<n-1;i++){
		int a,b;
		cin >> a >> b;
		e[a].push_back(b);
		e[b].push_back(a);
	}
	dfs(1);
	cout << res << "\n";
}


#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using vi = vector<int>;

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

}


#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using vi = vector<int>;
int n,k;
ll res;

const int MAX = 2e5+10;
ll s[MAX][5];
ll q[MAX][5];
vi e[MAX];
int v[MAX];

void dfs(int x){
	v[x] = 1;
	q[x][0] += 1;
	for(int y: e[x]){
		if( v[y] ) continue;
		dfs(y);
		for(int i=0;i<k;i++){
			for(int j=0;j<k;j++){
				res += s[x][i]*q[y][j];
				res += s[y][j]*q[x][i];
				int c1 = (i + j +1)/k;
				if( (i+j+1)%k) c1 ++;
				int c2 = i/k + j/k;
				if( i%k) c2++;
				if( j%k ) c2++;
				res += q[x][i]*q[y][j]*(c1-c2);
			}
		}
		for(int i=0;i<k;i++){
			q[x][(i+1)%k] += q[y][i];
			s[x][(i+1)%k] += s[y][i];
		}
		s[x][1%k] += q[y][0];
	}
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n >> k;
	for(int i=0;i<n-1;i++){
		int a,b;
		cin >> a >> b;
		e[a].push_back(b);
		e[b].push_back(a);
	}
	dfs(1);
	cout << res << "\n";
}


#include <bits/stdc++.h>
using namespace std;

#ifdef LOCAL
#define DEBUG(...) debug(#__VA_ARGS__, __VA_ARGS__);
#else
#define DEBUG(...)
#endif

template<typename T, typename S> ostream& operator << (ostream &os, const pair<T, S> &p) {return os << "(" << p.first << ", " << p.second << ")";}
template<typename C, typename T = decay<decltype(*begin(declval<C>()))>, typename enable_if<!is_same<C, string>::value>::type* = nullptr>
ostream& operator << (ostream &os, const C &c) {bool f = true; os << "["; for (const auto &x : c) {if (!f) os << ", "; f = false; os << x;} return os << "]";}
template<typename T> void debug(string s, T x) {cerr << s << " = " << x << "\n";}
template<typename T, typename... Args> void debug(string s, T x, Args... args) {cerr << s.substr(0, s.find(',')) << " = " << x << " | "; debug(s.substr(s.find(',') + 2), args...);}

int k;
long long dp[200000][5], numPaths[200000][5];
vector<int> adj[200000];

void dfsInit(int u, int p) {
    for (int v : adj[u])
        if (v != p) {
            dfsInit(v, u);
            for (int i=0; i<k; i++) {
                dp[u][(i+1)%k] += dp[v][i] + (i == 0 ? numPaths[v][i] + 1 : 0);
                numPaths[u][(i+1)%k] += numPaths[v][i] + (i == 0);
            }
        }
}

long long dfsReroot(int u, int p) {
    long long ret = 0;
    for (int i=0; i<k; i++)
        ret += dp[u][i%k];

    for (int v : adj[u])
        if (v != p) {
            for (int i=0; i<k; i++) {
                dp[u][(i+1)%k] -= dp[v][i] + (i == 0 ? numPaths[v][i] + 1 : 0);
                numPaths[u][(i+1)%k] -= numPaths[v][i] + (i == 0);
            }
            for (int i=0; i<k; i++) {
                dp[v][(i+1)%k] += dp[u][i] + (i == 0 ? numPaths[u][i] + 1 : 0);
                numPaths[v][(i+1)%k] += numPaths[u][i] + (i == 0);
            }

            ret += dfsReroot(v, u);

            for (int i=0; i<k; i++) {
                dp[v][(i+1)%k] -= dp[u][i] + (i == 0 ? numPaths[u][i] + 1 : 0);
                numPaths[v][(i+1)%k] -= numPaths[u][i] + (i == 0);
            }
            for (int i=0; i<k; i++) {
                dp[u][(i+1)%k] += dp[v][i] + (i == 0 ? numPaths[v][i] + 1 : 0);
                numPaths[u][(i+1)%k] += numPaths[v][i] + (i == 0);
            }
        }
    return ret;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    int n;
    cin >> n >> k;
    for (int i=0; i<n-1; i++) {
        int a, b;
        cin >> a >> b;
        adj[a-1].push_back(b-1);
        adj[b-1].push_back(a-1);
    }

    dfsInit(0, -1);
    cout << dfsReroot(0, -1) / 2 << "\n";

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

#define fast { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define pb push_back
#define ll int
#define ld long double
#define sz(x) (ll)x.size()

#define vi vector<int>
#define vl vector<long>
#define vll vector<long long>

#define infi INT_MAX
#define infl LONG_LONG_MAX
#define infd LDBL_MAX
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fi(i,a,b) for(ll i=(b-1);i>=a;i--)
#define F first
#define S second
#define G(a,b) get<a>(b)
#define MP make_pair
#define MT make_tuple
#define pll pair<ll,ll>
//#define endl "\n"
#define ALL(v) v.begin(),v.end()
#define nl cout<<"\n";
#define pr(x) cout<<x;
#define pr1(x) cout<<x<<" ";
#define pr2(x,y) cout<<x<<" "<<y;
#define pr3(x,y,z) cout<<x<<" "<<y<<" "<<z;
#define pr4(x,y,z,w) cout<<x<<" "<<y<<" "<<z<<" "<<w;
#define deb printf("***************************************************************************************\n");
#define moshi printf("moshi moshi ! \n");
#define hi printf("hi ! \n");
#define bye printf("bye bye ! \n");
#define o_set(ll) tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define number_of_set_bits  __builtin_popcountll
const ld PI=3.1415926535897932384626433;

//template<typename T>
//#define o_set(T) tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>
//member functions :
//1. order_of_key(k) : number of elements strictly lesser than k
//2. find_by_order(k) : k-th element in the set

//const ll N=1e6+7;
ll p=1e9+7;
//ll fac[N];

ll gcd(ll a, ll b)
{
   if (a == 0) return b;
   return gcd(b % a, a);
}

inline ll ceil(ll a,ll b)
{
   return (a+b-1)/b;
}

ll max(ll x,ll y,ll z)
{
   return max(x,max(y,z));
}

ll min(ll x,ll y,ll z)
{
   return min(x,min(y,z));
}

ll modpro(ll x,ll y,ll z=1)
{
   x%=p;
   y%=p;
   z%=p;
   ll res=(x*y)%p;
   res=(res*z)%p;
   return res;
}

ll modadd(ll x,ll y,ll z=0)
{
   x%=p;
   y%=p;
   z%=p;
   ll res=(x+y)%p;
   res=(res+z)%p;
   return res;
}

ll pow_mod_p(ll a,ll b)
{
   a=a%p;
   ll res=1;
   while(b>0)
   {
     if(b&1) res=(res*a)%p;
     b=b>>1;
     a=(a*a)%p;
   }
   return res;
}

inline ll mod_inv(ll x)
{
   return pow_mod_p(x,p-2);
}
/*
const ll N=5e5+5;
ll dp[N],fac[N];

// Don't forget to set fac[0]=1
ll nCr(ll x,ll y)
{
   if(x<y) return 0;
   ll res=fac[x];
   ll den=(fac[y]*fac[x-y])%p;
   ll deni=mod_inv(den);
   res=(res*deni)%p;
   return res;
}*/

ll is_set(ll a,ll i)
{
   if( ( a & ((ll)1<<i) ) == 0 ) return 0;
   else return 1;
}

//  Comparator should follow :
//  1: x<=y or y<=x uniquely
//  2: Transitivity : a<=b and b<=c implies a<=c
//  3: Anti-Symmetry: a<=b and b<=a implies a=b
// return 1 to put x before y in sorted order
inline bool comp(pll &x,pll &y)
{
   if(x.F<y.F) return 1;
   else if(x.F==y.F)
   {
      if(x.S>y.S) return 1;
      else return 0;
   }
   return 0;
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }
    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

// resize : str.resize(new_size)   new size <= old size

// for Vector :
// lower_bound(starting iterator , iterator next to end , value)  :  iterator to first element greater than or equal to value
// upper_bound(starting iterator , iterator next to end , value)  :  iterator to first element strictly greater than value

// For Set :      s.lower_bound(value)
// if no such element exists they return  vector.end() or s.end()

// x bits : [x-1 , x-2 , .... , 1(1st bit) , 0(0th bit)] =>   leftmost 1 at 2^(x-1)    max number that can be represented : 2^(x) -1
// 63 bits is greater than 10^18

// 1<<x  :  2 ^ x  (left shift)

// Min heap :  priority_queue < ll , vector<ll>, greater<ll> > q
// Max heap :  priority_queue < ll > q
    // Set in descending order  :   set< ll,greater <ll> >

// While debugging :
// 1 : check if array size is correct  :  It may give unexpected results
// 2 : check if you have swapped i and j at some part of program
// 3 : for string check if you are trying to acces  index = -1

// Bitwise Tricks :
// 1 : While using 1<<i  use (ll)1<<i  because in former one "1" is considered as int
// 2 : To flip first k-bits of a number :  x xor (2^k-1)  or x ^ (((ll)1<<k)-1)  : 2^k-1 is the largest number of k bits
// 3 : To flip k-th bit (0-based)  :  x xor (2^k)  or  x ^ ((ll)1<<k)
// 4 : To set k-th bit (0-based)   :  x or (2^k)   or  x | ((ll)1<<k)
// 5 : To un-set k-th bit (0-based)   :  x & (~ ((ll)1<<k) )

// To prove Greedy :
// 1 : Optimal Choice at each step
// 2 : Exchange Argument
// 3 : Find a lower or upper bound on answer and then construct an answer for that bound
// 4 : Find properties which Optimal Solution must satisfy ( This can be useful to deduce form of Optimal answer)

// Erase one occurrence in multiset : it=s.find(element)   s.erase(it)
// putchar('a'+j) : to print (j+1)th character
// getline(cin,str) : To input string until newline

void lps(string &pp,ll *lps)
{
   ll xx=pp.length();
   //ll lps[xx]={};
   f(i,1,xx)
   {
       ll j=lps[i-1];
       while(j>0 && pp[j]!=pp[i]) j=lps[j-1];
       if(pp[i]==pp[j]) j++;
       lps[i]=j;
   }
}

// Remember to take input string as  getline(cin,s)
void stoi(string &s,vll &v)
{
   stringstream str(s);
   ll x;
   while(str>>x)
   {
       v.pb(x);
   }
}

void Miden(ll **p1,ll n)
{
    ll (*x)[n]=(ll(*)[n]) p1;
    f(i,0,n)
    {
        f(j,0,n)
        {
            x[i][j]=0;
        }
        x[i][i]=1;
    }
    return;
}

void Mmult(ll **p1,ll **p2,ll **ans,ll x,ll y,ll z,ll m)
{
    ll (*a)[y]=(ll (*)[y])p1;
    ll (*b)[z]=(ll (*)[z])p2;
    ll (*c)[z]=(ll (*)[z])ans;
    f(i,0,x)
    {
        f(j,0,z)
        {
            c[i][j]=0;
            f(k,0,y)
            {
                c[i][j]+=a[i][k]*b[k][j];
                c[i][j]%=m;
            }
        }
    }
    return;
}

void Mpow(ll **p1,ll **ans,ll n,ll y,ll m)
{
    if(y==0)
    {
        Miden(ans,n);
        return;
    }
    ll t[n][n];
    Mpow(p1,(ll **)t,n,y/2,m);
    ll z[n][n];
    Mmult((ll **)t,(ll **)t,(ll **)z,n,n,n,m);
    if(y%2)
    {
        Mmult((ll **)z,p1,ans,n,n,n,m);
    }
    else
    {
        Miden((ll **)t,n);
        Mmult((ll **)z,(ll **)t,ans,n,n,n,m);
    }
    return;
}

void debg(ll *arr,ll l,ll r)
{
  f(i,l,r+1) pr1(arr[i])
  nl
}

void exit()
{
  cout<<"-1\n";
  exit(0);
}

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
    template <typename Arg1>
    void __f(const char* name, Arg1&& arg1){
        cout << name << " : " << arg1 << std::endl;
        //use cerr if u want to display at the bottom
    }
    template <typename Arg1, typename... Args>
    void __f(const char* names, Arg1&& arg1, Args&&... args){
        const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
    }
#else
#define trace(...)
#endif

#define endl "\n"

const ll N=2e5+5;
ll n,k,in[N],out[N],dp1[N][5],dp2[N][5];
list<ll>adj[N];

void dfs(ll v=1,ll pv=0)
{
  dp1[v][0]=1;
  for(auto i:adj[v])
  {
    if(i==pv) continue;
    dfs(i,v);
    f(z,0,k) dp1[v][(z+1)%k]+=dp1[i][z];
    in[v]+=in[i]+dp1[i][0];
  }
}

void dfs2(ll v=1,ll pv=0)
{
  for(auto i:adj[v])
  {
    if(i==pv) continue;
    out[i]=in[v]-(in[i]+dp1[i][0])+dp1[v][0]-dp1[i][k-1]+(out[v]+dp2[v][0]);
    f(z,0,k) dp2[i][(z+1)%k]+=dp2[v][z];
    f(z,0,k) dp2[i][(z+1)%k]+=( dp1[v][z]-dp1[i][(z-1+k)%k]  );
    dfs2(i,v);
  }
}

void func()
{
  cin>>n>>k;
  f(i,1,n)
  {
    ll u,v;
    cin>>u>>v;
    adj[u].pb(v);
    adj[v].pb(u);
  }
  dfs();
  dfs2();
  ll ans=0;
  f(i,1,n+1) ans+=in[i]+out[i];
  ans/=2;
  pr(ans) nl
}

int main()
{
    fast
    //#ifndef ONLINE_JUDGE
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    //#endif // ONLINE_JUDGE

    ll ntc=1;
    //cin>>ntc;

    f(i,1,ntc+1)
    {
      //cout<<"Case #"<<i<<": ";
       func();
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

#define fast { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define pb push_back
#define ll long long
#define ld long double
#define sz(x) (ll)x.size()

#define vi vector<int>
#define vl vector<long>
#define vll vector<long long>

#define infi INT_MAX
#define infl LONG_LONG_MAX
#define infd LDBL_MAX
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fi(i,a,b) for(ll i=(b-1);i>=a;i--)
#define F first
#define S second
#define G(a,b) get<a>(b)
#define MP make_pair
#define MT make_tuple
#define pll pair<ll,ll>
//#define endl "\n"
#define ALL(v) v.begin(),v.end()
#define nl cout<<"\n";
#define pr(x) cout<<x;
#define pr1(x) cout<<x<<" ";
#define pr2(x,y) cout<<x<<" "<<y;
#define pr3(x,y,z) cout<<x<<" "<<y<<" "<<z;
#define pr4(x,y,z,w) cout<<x<<" "<<y<<" "<<z<<" "<<w;
#define deb printf("***************************************************************************************\n");
#define moshi printf("moshi moshi ! \n");
#define hi printf("hi ! \n");
#define bye printf("bye bye ! \n");
#define o_set(ll) tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define number_of_set_bits  __builtin_popcountll
const ld PI=3.1415926535897932384626433;

//template<typename T>
//#define o_set(T) tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>
//member functions :
//1. order_of_key(k) : number of elements strictly lesser than k
//2. find_by_order(k) : k-th element in the set

//const ll N=1e6+7;
ll p=1e9+7;
//ll fac[N];

ll gcd(ll a, ll b)
{
   if (a == 0) return b;
   return gcd(b % a, a);
}

inline ll ceil(ll a,ll b)
{
   return (a+b-1)/b;
}

ll max(ll x,ll y,ll z)
{
   return max(x,max(y,z));
}

ll min(ll x,ll y,ll z)
{
   return min(x,min(y,z));
}

ll modpro(ll x,ll y,ll z=1)
{
   x%=p;
   y%=p;
   z%=p;
   ll res=(x*y)%p;
   res=(res*z)%p;
   return res;
}

ll modadd(ll x,ll y,ll z=0)
{
   x%=p;
   y%=p;
   z%=p;
   ll res=(x+y)%p;
   res=(res+z)%p;
   return res;
}

ll pow_mod_p(ll a,ll b)
{
   a=a%p;
   ll res=1;
   while(b>0)
   {
     if(b&1) res=(res*a)%p;
     b=b>>1;
     a=(a*a)%p;
   }
   return res;
}

inline ll mod_inv(ll x)
{
   return pow_mod_p(x,p-2);
}
/*
const ll N=5e5+5;
ll dp[N],fac[N];

// Don't forget to set fac[0]=1
ll nCr(ll x,ll y)
{
   if(x<y) return 0;
   ll res=fac[x];
   ll den=(fac[y]*fac[x-y])%p;
   ll deni=mod_inv(den);
   res=(res*deni)%p;
   return res;
}*/

ll is_set(ll a,ll i)
{
   if( ( a & ((ll)1<<i) ) == 0 ) return 0;
   else return 1;
}

//  Comparator should follow :
//  1: x<=y or y<=x uniquely
//  2: Transitivity : a<=b and b<=c implies a<=c
//  3: Anti-Symmetry: a<=b and b<=a implies a=b
// return 1 to put x before y in sorted order
inline bool comp(pll &x,pll &y)
{
   if(x.F<y.F) return 1;
   else if(x.F==y.F)
   {
      if(x.S>y.S) return 1;
      else return 0;
   }
   return 0;
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }
    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

// resize : str.resize(new_size)   new size <= old size

// for Vector :
// lower_bound(starting iterator , iterator next to end , value)  :  iterator to first element greater than or equal to value
// upper_bound(starting iterator , iterator next to end , value)  :  iterator to first element strictly greater than value

// For Set :      s.lower_bound(value)
// if no such element exists they return  vector.end() or s.end()

// x bits : [x-1 , x-2 , .... , 1(1st bit) , 0(0th bit)] =>   leftmost 1 at 2^(x-1)    max number that can be represented : 2^(x) -1
// 63 bits is greater than 10^18

// 1<<x  :  2 ^ x  (left shift)

// Min heap :  priority_queue < ll , vector<ll>, greater<ll> > q
// Max heap :  priority_queue < ll > q
    // Set in descending order  :   set< ll,greater <ll> >

// While debugging :
// 1 : check if array size is correct  :  It may give unexpected results
// 2 : check if you have swapped i and j at some part of program
// 3 : for string check if you are trying to acces  index = -1

// Bitwise Tricks :
// 1 : While using 1<<i  use (ll)1<<i  because in former one "1" is considered as int
// 2 : To flip first k-bits of a number :  x xor (2^k-1)  or x ^ (((ll)1<<k)-1)  : 2^k-1 is the largest number of k bits
// 3 : To flip k-th bit (0-based)  :  x xor (2^k)  or  x ^ ((ll)1<<k)
// 4 : To set k-th bit (0-based)   :  x or (2^k)   or  x | ((ll)1<<k)
// 5 : To un-set k-th bit (0-based)   :  x & (~ ((ll)1<<k) )

// To prove Greedy :
// 1 : Optimal Choice at each step
// 2 : Exchange Argument
// 3 : Find a lower or upper bound on answer and then construct an answer for that bound
// 4 : Find properties which Optimal Solution must satisfy ( This can be useful to deduce form of Optimal answer)

// Erase one occurrence in multiset : it=s.find(element)   s.erase(it)
// putchar('a'+j) : to print (j+1)th character
// getline(cin,str) : To input string until newline

void lps(string &pp,ll *lps)
{
   ll xx=pp.length();
   //ll lps[xx]={};
   f(i,1,xx)
   {
       ll j=lps[i-1];
       while(j>0 && pp[j]!=pp[i]) j=lps[j-1];
       if(pp[i]==pp[j]) j++;
       lps[i]=j;
   }
}

// Remember to take input string as  getline(cin,s)
void stoi(string &s,vll &v)
{
   stringstream str(s);
   ll x;
   while(str>>x)
   {
       v.pb(x);
   }
}

void Miden(ll **p1,ll n)
{
    ll (*x)[n]=(ll(*)[n]) p1;
    f(i,0,n)
    {
        f(j,0,n)
        {
            x[i][j]=0;
        }
        x[i][i]=1;
    }
    return;
}

void Mmult(ll **p1,ll **p2,ll **ans,ll x,ll y,ll z,ll m)
{
    ll (*a)[y]=(ll (*)[y])p1;
    ll (*b)[z]=(ll (*)[z])p2;
    ll (*c)[z]=(ll (*)[z])ans;
    f(i,0,x)
    {
        f(j,0,z)
        {
            c[i][j]=0;
            f(k,0,y)
            {
                c[i][j]+=a[i][k]*b[k][j];
                c[i][j]%=m;
            }
        }
    }
    return;
}

void Mpow(ll **p1,ll **ans,ll n,ll y,ll m)
{
    if(y==0)
    {
        Miden(ans,n);
        return;
    }
    ll t[n][n];
    Mpow(p1,(ll **)t,n,y/2,m);
    ll z[n][n];
    Mmult((ll **)t,(ll **)t,(ll **)z,n,n,n,m);
    if(y%2)
    {
        Mmult((ll **)z,p1,ans,n,n,n,m);
    }
    else
    {
        Miden((ll **)t,n);
        Mmult((ll **)z,(ll **)t,ans,n,n,n,m);
    }
    return;
}

void debg(ll *arr,ll l,ll r)
{
  f(i,l,r+1) pr1(arr[i])
  nl
}

void exit()
{
  cout<<"-1\n";
  exit(0);
}

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
    template <typename Arg1>
    void __f(const char* name, Arg1&& arg1){
        cout << name << " : " << arg1 << std::endl;
        //use cerr if u want to display at the bottom
    }
    template <typename Arg1, typename... Args>
    void __f(const char* names, Arg1&& arg1, Args&&... args){
        const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
    }
#else
#define trace(...)
#endif

#define endl "\n"

const ll N=2e5+5;
ll n,k,in[N],out[N],dp1[N][5],dp2[N][5];
list<ll>adj[N];

void dfs(ll v=1,ll pv=0)
{
  dp1[v][0]=1;
  for(auto i:adj[v])
  {
    if(i==pv) continue;
    dfs(i,v);
    f(z,0,k) dp1[v][(z+1)%k]+=dp1[i][z];
    in[v]+=in[i]+dp1[i][0];
  }
}

void dfs2(ll v=1,ll pv=0)
{
  for(auto i:adj[v])
  {
    if(i==pv) continue;
    out[i]=in[v]-(in[i]+dp1[i][0])+dp1[v][0]-dp1[i][k-1]+(out[v]+dp2[v][0]);
    f(z,0,k) dp2[i][(z+1)%k]+=dp2[v][z];
    f(z,0,k) dp2[i][(z+1)%k]+=( dp1[v][z]-dp1[i][(z-1+k)%k]  );
    dfs2(i,v);
  }
}

void func()
{
  cin>>n>>k;
  f(i,1,n)
  {
    ll u,v;
    cin>>u>>v;
    adj[u].pb(v);
    adj[v].pb(u);
  }
  dfs();
  dfs2();
  ll ans=0;
  f(i,1,n+1) ans+=in[i]+out[i];
  ans/=2;
  pr(ans) nl
}

int main()
{
    fast
    //#ifndef ONLINE_JUDGE
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    //#endif // ONLINE_JUDGE

    ll ntc=1;
    //cin>>ntc;

    f(i,1,ntc+1)
    {
      //cout<<"Case #"<<i<<": ";
       func();
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

#define fast { ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0); }
#define pb push_back
#define ll long long
#define ld long double
#define sz(x) (ll)x.size()

#define vi vector<int>
#define vl vector<long>
#define vll vector<long long>

#define infi INT_MAX
#define infl LONG_LONG_MAX
#define infd LDBL_MAX
#define f(i,a,b) for(ll i=a;i<b;i++)
#define fi(i,a,b) for(ll i=(b-1);i>=a;i--)
#define F first
#define S second
#define G(a,b) get<a>(b)
#define MP make_pair
#define MT make_tuple
#define pll pair<ll,ll>
//#define endl "\n"
#define ALL(v) v.begin(),v.end()
#define nl cout<<"\n";
#define pr(x) cout<<x;
#define pr1(x) cout<<x<<" ";
#define pr2(x,y) cout<<x<<" "<<y;
#define pr3(x,y,z) cout<<x<<" "<<y<<" "<<z;
#define pr4(x,y,z,w) cout<<x<<" "<<y<<" "<<z<<" "<<w;
#define deb printf("***************************************************************************************\n");
#define moshi printf("moshi moshi ! \n");
#define hi printf("hi ! \n");
#define bye printf("bye bye ! \n");
#define o_set(ll) tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define number_of_set_bits  __builtin_popcountll
const ld PI=3.1415926535897932384626433;

//template<typename T>
//#define o_set(T) tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>
//member functions :
//1. order_of_key(k) : number of elements strictly lesser than k
//2. find_by_order(k) : k-th element in the set

//const ll N=1e6+7;
ll p=1e9+7;
//ll fac[N];

ll gcd(ll a, ll b)
{
   if (a == 0) return b;
   return gcd(b % a, a);
}

inline ll ceil(ll a,ll b)
{
   return (a+b-1)/b;
}

ll max(ll x,ll y,ll z)
{
   return max(x,max(y,z));
}

ll min(ll x,ll y,ll z)
{
   return min(x,min(y,z));
}

ll modpro(ll x,ll y,ll z=1)
{
   x%=p;
   y%=p;
   z%=p;
   ll res=(x*y)%p;
   res=(res*z)%p;
   return res;
}

ll modadd(ll x,ll y,ll z=0)
{
   x%=p;
   y%=p;
   z%=p;
   ll res=(x+y)%p;
   res=(res+z)%p;
   return res;
}

ll pow_mod_p(ll a,ll b)
{
   a=a%p;
   ll res=1;
   while(b>0)
   {
     if(b&1) res=(res*a)%p;
     b=b>>1;
     a=(a*a)%p;
   }
   return res;
}

inline ll mod_inv(ll x)
{
   return pow_mod_p(x,p-2);
}
/*
const ll N=5e5+5;
ll dp[N],fac[N];

// Don't forget to set fac[0]=1
ll nCr(ll x,ll y)
{
   if(x<y) return 0;
   ll res=fac[x];
   ll den=(fac[y]*fac[x-y])%p;
   ll deni=mod_inv(den);
   res=(res*deni)%p;
   return res;
}*/

ll is_set(ll a,ll i)
{
   if( ( a & ((ll)1<<i) ) == 0 ) return 0;
   else return 1;
}

//  Comparator should follow :
//  1: x<=y or y<=x uniquely
//  2: Transitivity : a<=b and b<=c implies a<=c
//  3: Anti-Symmetry: a<=b and b<=a implies a=b
// return 1 to put x before y in sorted order
inline bool comp(pll &x,pll &y)
{
   if(x.F<y.F) return 1;
   else if(x.F==y.F)
   {
      if(x.S>y.S) return 1;
      else return 0;
   }
   return 0;
}

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }
    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

// resize : str.resize(new_size)   new size <= old size

// for Vector :
// lower_bound(starting iterator , iterator next to end , value)  :  iterator to first element greater than or equal to value
// upper_bound(starting iterator , iterator next to end , value)  :  iterator to first element strictly greater than value

// For Set :      s.lower_bound(value)
// if no such element exists they return  vector.end() or s.end()

// x bits : [x-1 , x-2 , .... , 1(1st bit) , 0(0th bit)] =>   leftmost 1 at 2^(x-1)    max number that can be represented : 2^(x) -1
// 63 bits is greater than 10^18

// 1<<x  :  2 ^ x  (left shift)

// Min heap :  priority_queue < ll , vector<ll>, greater<ll> > q
// Max heap :  priority_queue < ll > q
    // Set in descending order  :   set< ll,greater <ll> >

// While debugging :
// 1 : check if array size is correct  :  It may give unexpected results
// 2 : check if you have swapped i and j at some part of program
// 3 : for string check if you are trying to acces  index = -1

// Bitwise Tricks :
// 1 : While using 1<<i  use (ll)1<<i  because in former one "1" is considered as int
// 2 : To flip first k-bits of a number :  x xor (2^k-1)  or x ^ (((ll)1<<k)-1)  : 2^k-1 is the largest number of k bits
// 3 : To flip k-th bit (0-based)  :  x xor (2^k)  or  x ^ ((ll)1<<k)
// 4 : To set k-th bit (0-based)   :  x or (2^k)   or  x | ((ll)1<<k)
// 5 : To un-set k-th bit (0-based)   :  x & (~ ((ll)1<<k) )

// To prove Greedy :
// 1 : Optimal Choice at each step
// 2 : Exchange Argument
// 3 : Find a lower or upper bound on answer and then construct an answer for that bound
// 4 : Find properties which Optimal Solution must satisfy ( This can be useful to deduce form of Optimal answer)

// Erase one occurrence in multiset : it=s.find(element)   s.erase(it)
// putchar('a'+j) : to print (j+1)th character
// getline(cin,str) : To input string until newline

void lps(string &pp,ll *lps)
{
   ll xx=pp.length();
   //ll lps[xx]={};
   f(i,1,xx)
   {
       ll j=lps[i-1];
       while(j>0 && pp[j]!=pp[i]) j=lps[j-1];
       if(pp[i]==pp[j]) j++;
       lps[i]=j;
   }
}

// Remember to take input string as  getline(cin,s)
void stoi(string &s,vll &v)
{
   stringstream str(s);
   ll x;
   while(str>>x)
   {
       v.pb(x);
   }
}

void Miden(ll **p1,ll n)
{
    ll (*x)[n]=(ll(*)[n]) p1;
    f(i,0,n)
    {
        f(j,0,n)
        {
            x[i][j]=0;
        }
        x[i][i]=1;
    }
    return;
}

void Mmult(ll **p1,ll **p2,ll **ans,ll x,ll y,ll z,ll m)
{
    ll (*a)[y]=(ll (*)[y])p1;
    ll (*b)[z]=(ll (*)[z])p2;
    ll (*c)[z]=(ll (*)[z])ans;
    f(i,0,x)
    {
        f(j,0,z)
        {
            c[i][j]=0;
            f(k,0,y)
            {
                c[i][j]+=a[i][k]*b[k][j];
                c[i][j]%=m;
            }
        }
    }
    return;
}

void Mpow(ll **p1,ll **ans,ll n,ll y,ll m)
{
    if(y==0)
    {
        Miden(ans,n);
        return;
    }
    ll t[n][n];
    Mpow(p1,(ll **)t,n,y/2,m);
    ll z[n][n];
    Mmult((ll **)t,(ll **)t,(ll **)z,n,n,n,m);
    if(y%2)
    {
        Mmult((ll **)z,p1,ans,n,n,n,m);
    }
    else
    {
        Miden((ll **)t,n);
        Mmult((ll **)z,(ll **)t,ans,n,n,n,m);
    }
    return;
}

void debg(ll *arr,ll l,ll r)
{
  f(i,l,r+1) pr1(arr[i])
  nl
}

void exit()
{
  cout<<"-1\n";
  exit(0);
}

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
    template <typename Arg1>
    void __f(const char* name, Arg1&& arg1){
        cout << name << " : " << arg1 << std::endl;
        //use cerr if u want to display at the bottom
    }
    template <typename Arg1, typename... Args>
    void __f(const char* names, Arg1&& arg1, Args&&... args){
        const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
    }
#else
#define trace(...)
#endif

#define endl "\n"

const ll N=2e5+5;
ll n,k,dp[N][5],g[N][5],szz[N],tot[5],l;
list<ll>adj[N];

void dfs(ll v=1,ll pv=0)
{
  dp[v][0]=1;
  szz[v]=1;
  for(auto i:adj[v])
  {
    if(i==pv) continue;
    dfs(i,v);
    f(z,0,k)  dp[v][(z+1)%k]+=dp[i][z];
    szz[v]+=szz[i];
  }

  ll cnt[k]={};
  for(auto i:adj[v])
  {
    if(i==pv) continue;
    f(z,0,k) cnt[z]=dp[v][z]-dp[i][(z-1+k)%k];
    f(z,0,k) f(w,0,k) g[v][(z+w+1)%k]+=(dp[i][z]*cnt[w]);
  }

  f(z,0,k) g[v][z]+=dp[v][z],g[v][z]/=2;
  f(z,0,k) tot[z]+=g[v][z];
  l+=(szz[v]*(n-szz[v]));
}

void func()
{
  cin>>n>>k;
  f(i,1,n)
  {
    ll u,v;
    cin>>u>>v;
    adj[u].pb(v);
    adj[v].pb(u);
  }
  dfs();

  ll ans=l;
  f(z,0,k)
  {
    ll req=k-z;
    if(z==0) req=0;
    ans+=(req*tot[z]);
  }
  ans/=k;
  pr(ans) nl
}

int main()
{
    fast
    //#ifndef ONLINE_JUDGE
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    //#endif // ONLINE_JUDGE

    ll ntc=1;
    //cin>>ntc;

    f(i,1,ntc+1)
    {
      //cout<<"Case #"<<i<<": ";
       func();
    }

    return 0;
}


#include <bits/stdc++.h>
#define lli long long int
#define pb push_back
#define mod 1000000007
#define mod2 998244353
#define MAXN 1000000000
#define v32 vector<int>
#define v64 vector<lli>
#define v1024 vector <vector <int>>
#define v4096 vector <vector <lli>>
#define vt vector
#define f(x, y, z) for (lli x = y; x < z; x++)
#define fd(x, y, z) for (lli x = y; x > z; x--)
#define lb lower_bound
#define ld long double
#define m64 map<lli,lli>
#define m32 map<int,int>
#define m64it map<lli,lli>::iterator
#define m32it map<int,int>::iterator
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define ist insert
#define p_q priority_queue
#define min_p_q priority_queue <int,vt <int>,greater <int>>
using namespace std;
lli tmod(lli x,lli m){return (x%m+m)%m;}//USE AT YOUR OWN RISK
v64 tree[200001];
lli depth[200001][5],depth_from_root[200001];
lli ans[200001],n,k;
void set_depth(int u,int p)
{
	depth[u][0]=1;
	for(auto x:tree[u])
      {
      	if(x==p)continue;
      	depth_from_root[x]=depth_from_root[u]+1;
      	set_depth(x,u);
      	f(i,0,k)
      	depth[u][i]+=depth[x][(i-1+k)%k];
      }
}
void solve(int u,int p)
{
   for(auto x:tree[u])
   {
   	 if(x==p)continue;
   	 lli temp[k];f(i,0,k)temp[i]=depth[x][i];
     f(i,0,k)
     depth[x][i]+=depth[u][(i-1+k)%k]-temp[(i-2+2*k)%k];
     ans[x]=ans[u]+depth[u][0]-temp[k-1]-temp[0];
     solve(x,u);
   }
}

int main()
{
  fastio;
  cin>>n>>k;
  f(i,0,n-1)
  {
  	int u,v;cin>>u>>v;
  	tree[u].pb(v),tree[v].pb(u);
  }
  set_depth(1,0);
  lli tans=0;
  f(i,1,n+1)
  {
  	tans+=depth_from_root[i]/k;
  	if(depth_from_root[i]%k!=0)tans++;
  }
  ans[1]=tans;
  solve(1,0);
  f(i,2,n+1)tans+=ans[i];
  cout<<tans/2;
  return 0;
}


#include<bits/stdc++.h>

using namespace std;
#define int long long
int n, k;
vector <vector <int> > cntdown, cntup, g;
long long ans = 0;
vector <int> _sz;
vector <int> lendown, lenup;
void dfs(int v, int p = -1)
{
	_sz[v] = 1;
	auto it = find(g[v].begin(), g[v].end(), p);
	if(it != g[v].end())
	{
		g[v].erase(it);
	}
	for(int i = 0; i < g[v].size(); i++)
	{
		int to = g[v][i];
		dfs(to, v);
		for(int j = 0; j < k; j++)
		{
			cntdown[v][(j + 1) % k] += cntdown[to][j];
		}
		cntdown[v][1 % k]++;
		lendown[v] += _sz[to] + lendown[to];
		_sz[v] += _sz[to];
	}
}
void dfs1(int v, int p = -1)
{
	for(int i = 0; i < g[v].size(); i++)
	{
		int to = g[v][i];
		lenup[to] = lenup[v] + (lendown[v] - _sz[to] - lendown[to]) + (n - _sz[to]);
		for(int j = 0; j < k; j++)
		{
			cntup[to][(j + 1) % k] += cntup[v][j];
			cntup[to][(j + 1) % k] += (cntdown[v][j] - cntdown[to][(j - 1 + k) % k]);
		}
		cntup[to][(2) % k]--;
		cntup[to][1 % k]++;
		dfs1(to, v);
	}
	int sum = (lenup[v] + lendown[v]);
	for(int j = 1; j < k; j++)
	{
		sum -= cntup[v][j] * j;
		sum -= cntdown[v][j] * j;
		sum += (cntup[v][j] + cntdown[v][j]) * k;
	}
	sum /= k;
	ans += sum;
}
signed main(){
//	ios_base::sync_with_stdio(false);
//	cin.tie(NULL);
//	cout.tie(NULL);
	cin >> n >> k;
	lendown.resize(n);
	lenup.resize(n);
	_sz.resize(n);
	g.resize(n);
	cntdown.resize(n, vector <int> (k));
	cntup.resize(n, vector <int> (k));
	for(int i = 0; i < n - 1; i++)
	{
		int a, b;
		cin >> a >> b;
		a--;
		b--;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	dfs(0);
	dfs1(0);
	cout << ans / 2;
	return 0;
}


#include<bits/stdc++.h>

using namespace std;
#define int long long
int n, k;
vector <vector <int> > cntdown, cntup, g;
long long ans = 0;
vector <int> _sz;
vector <int> lendown, lenup;
void dfs(int v, int p = -1)
{
	_sz[v] = 1;
	auto it = find(g[v].begin(), g[v].end(), p);
	if(it != g[v].end())
	{
		g[v].erase(it);
	}
	for(int i = 0; i < g[v].size(); i++)
	{
		int to = g[v][i];
		dfs(to, v);
		for(int j = 0; j < k; j++)
		{
			cntdown[v][(j + 1) % k] += cntdown[to][j];
		}
		cntdown[v][1]++;
		lendown[v] += _sz[to] + lendown[to];
		_sz[v] += _sz[to];
	}
}
void dfs1(int v, int p = -1)
{
	for(int i = 0; i < g[v].size(); i++)
	{
		int to = g[v][i];
		lenup[to] = lenup[v] + (lendown[v] - _sz[to] - lendown[to]) + (n - _sz[to]);
		for(int j = 0; j < k; j++)
		{
			cntup[to][(j + 1) % k] += cntup[v][j];
			cntup[to][(j + 1) % k] += (cntdown[v][j] - cntdown[to][(j - 1 + k) % k]);
		}
		cntup[to][(2) % k]--;
		cntup[to][1]++;
		dfs1(to, v);
	}
	int sum = (lenup[v] + lendown[v]);
	for(int j = 1; j < k; j++)
	{
		sum -= cntup[v][j] * j;
		sum -= cntdown[v][j] * j;
		sum += (cntup[v][j] + cntdown[v][j]) * k;
	}
	sum /= k;
	ans += sum;
}
signed main(){
//	ios_base::sync_with_stdio(false);
//	cin.tie(NULL);
//	cout.tie(NULL);
	cin >> n >> k;
	lendown.resize(n);
	lenup.resize(n);
	_sz.resize(n);
	g.resize(n);
	cntdown.resize(n, vector <int> (k));
	cntup.resize(n, vector <int> (k));
	for(int i = 0; i < n - 1; i++)
	{
		int a, b;
		cin >> a >> b;
		a--;
		b--;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	dfs(0);
	dfs1(0);
	cout << ans / 2;
	return 0;
}


#include<bits/stdc++.h>

using namespace std;
#define int long long
int n, k;
vector <vector <int> > cntdown, cntup, g;
long long ans = 0;
vector <int> _sz;
vector <int> lendown, lenup;
void dfs(int v, int p = -1)
{
	_sz[v] = 1;
	auto it = find(g[v].begin(), g[v].end(), p);
	if(it != g[v].end())
	{
		g[v].erase(it);
	}
	for(int i = 0; i < g[v].size(); i++)
	{
		int to = g[v][i];
		dfs(to, v);
		for(int j = 0; j < k; j++)
		{
			cntdown[v][(j + 1) % k] += cntdown[to][j];
		}
		cntdown[v][1]++;
		lendown[v] += _sz[to] + lendown[to];
		_sz[v] += _sz[to];
	}
}
void dfs1(int v, int p = -1)
{
	for(int i = 0; i < g[v].size(); i++)
	{
		int to = g[v][i];
		lenup[to] = lenup[v] + (lendown[v] - _sz[to] - lendown[to]) + (n - _sz[to]);
		for(int j = 0; j < k; j++)
		{
			cntup[to][(j + 1) % k] += cntup[v][j];
			cntup[to][(j + 1) % k] += (cntdown[v][j] - cntdown[to][(j - 1 + k) % k]);
		}
		cntup[to][(2) % k]--;
		cntup[to][1 % k]++;
		dfs1(to, v);
	}
	int sum = (lenup[v] + lendown[v]);
	for(int j = 1; j < k; j++)
	{
		sum -= cntup[v][j] * j;
		sum -= cntdown[v][j] * j;
		sum += (cntup[v][j] + cntdown[v][j]) * k;
	}
	sum /= k;
	ans += sum;
}
signed main(){
//	ios_base::sync_with_stdio(false);
//	cin.tie(NULL);
//	cout.tie(NULL);
	cin >> n >> k;
	lendown.resize(n);
	lenup.resize(n);
	_sz.resize(n);
	g.resize(n);
	cntdown.resize(n, vector <int> (k));
	cntup.resize(n, vector <int> (k));
	for(int i = 0; i < n - 1; i++)
	{
		int a, b;
		cin >> a >> b;
		a--;
		b--;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	dfs(0);
	dfs1(0);
	cout << ans / 2;
	return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <map>
#include <algorithm>
#include <iomanip>
#include <queue>
#include <utility>
#include <set>
#include <unordered_set>
#include <stack>
#include <iterator>
#include <random>
#include <fstream>
#include <chrono>
using namespace std;
#define forn(n) for(int i = 0; i < n; i++)
#define int long long
int n,k;
int ans;
void fast(){
    ios_base:: sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
}
const int max_n=4e5+10;
vector<vector<int>>g(max_n);
vector<int>s[5];
vector<int>cnt[5];
vector<bool>u;
int s_all[5], cnt_all[5];
void dfs(int v){
    //sum,cnt
    u[v]=1;
    //cnt[v]++;
    vector<int> sons;
    for(auto to:g[v]){
        if(!u[to]){
            dfs(to);
            sons.push_back(to);
        }
    }
    for(auto to:sons){
        for (int i = 0; i < k; i++) {
            for (int j = 0; j < k; j++) {
                cnt_all[(i + j + 1) % k] += cnt[i][v] * (cnt[j][to] + (j == 0));
                s_all[(i + j + 1) % k] += s[i][v] * (cnt[j][to] + (j == 0)) + (s[j][to] + cnt[j][to] + (j == 0))
                                                                              * cnt[i][v];
            }
        }
        for (int i = 0; i < k; i++) {
            s[(i + 1) % k][v] += s[i][to] + cnt[i][to] + (i == 0);
            cnt[(i + 1) % k][v] += (i == 0) + cnt[i][to];
        }
    }
    for (int i = 0; i < k; i++) {
        cnt_all[i] += cnt[i][v];
        s_all[i] += s[i][v];
    }
}
int32_t main()
{
    fast();
    cin >> n >> k;
    for(int i = 0; i < k; ++i) {
        s[i].resize(n);
        cnt[i].resize(n);
    }
    u.resize(n);
    for(int i = 0; i < n-1 ;++i){
        int x,y;
        cin >> x >> y;
        x--; y--;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    dfs(0);
    int ans = 0;
    for (int i = 0; i < k; i++) {
        if (i == 0) {
            ans += s_all[i] / k;
        } else {
            ans += (s_all[i] + (k - i) * cnt_all[i]) / k;
        }
    }
    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std  ;
#define ll long long
#define pb push_back
ll n , k , sum ;
const int N = 3 * 1e5 + 7 ;
vector<ll>adj[N] ;
ll sz[N] ;
ll dp[N][10] ;
void dfs1 (ll v , ll p) {
    sz[v] = 1 ;
    for (auto it : adj[v]) {
        if (it == p) continue ;
        dfs1(it,v) ;
        sz[v] += sz[it] ;
    }
    sum+= (sz[v] * (n- sz[v])) ;

}
void dfs2 (ll v , ll p ) {
    dp[v][0] = 1 ;
    int i , j ;
    for (auto it : adj[v]) {
        if (it==p) continue ;
        dfs2(it,v) ;
        for (i = 0;  i< k ; i++) {
            for (j = 0;  j < k ; j++) {
                ll rem = (i+j+1)%k ;
                rem = (k - rem)%k ;
                sum += (dp[it][i]*dp[v][j]*rem) ;
            }
        }
        for(i = 0 ; i< k ; i++)
            dp[v][(i+1)%k]+= dp[it][i] ;
    }

}

int main() {
    int i , u , v ;
    cin >> n >> k ;
    for (i =1 ; i< n ; i++) {
        cin >> u >> v ;
        adj[u].pb(v) , adj[v].pb(u) ;
    }
    dfs1(1,0) ;
    dfs2(1,0) ;
    cout << sum/k << endl ;
    return 0 ;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define ld long double
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
const int M=2e5+5;
std::vector<int> vtr[M];
ll sub[M],dst[M][5],ans,cur[5],k;
void dfs(int x,int p)
{
	sub[x]=1;
	dst[x][0]=1;
	for(auto u:vtr[x])
	{
		if(u!=p)
		{
			dfs(u,x);
			sub[x]+=sub[u];
			for(ll j=0;j<k;j++)
				dst[x][(j+1)%k] += dst[u][j];
		}
	}
}
void solve(int x,int p,ll d,vector<ll> cur)
{
	ll z=d;
	for(ll j=0;j<k;j++)
		cur[j] += dst[x][j];
	for(ll j=1;j<k;j++)
		z+=(k-j)*cur[j];
	// cout<<z<<" "<<x<<endl;
	ans += z/k;
	for(auto u:vtr[x])
	{
		if(u==p)
			continue;
		ll nd = d -sub[u]+sub[1]-sub[u];
		std::vector<ll> nc = cur;
		for(ll j=0;j<k;j++)
			nc[(j+1)%k]-=dst[u][j];
		std::vector<ll> nc2(k,0);
		for(ll j=0;j<k;j++)
		{
			nc2[(j+1)%k]=nc[j];
		}
		solve(u,x,nd,nc2);
	}
}
int main()
{
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	int n;
	cin>>n>>k;
	for(int i=1;i<n;i++)
	{
		int u,v;
		cin>>u>>v;
		vtr[u].pb(v);
		vtr[v].pb(u);
	}
	dfs(1,-1);
	ll d=0;
	for(int i=1;i<=n;i++)
		d+=sub[i]-1;
	vector<ll> cur(k,0);
	solve(1,-1,d,cur);
	cout<<ans/2<<"\n";
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
long long dp[N][6], ans[N], sz[N], rtr;
int n, k;
vector<int> gr[N];
void shift(int v) {
	int cnt = dp[v][k - 1];
	for (int i = k - 1; i > 0; i--)
		dp[v][i] = dp[v][i - 1];
	dp[v][0] = cnt;
	ans[v] += cnt;
}
void dfs(int v, int par = -1) {
	for (auto u : gr[v]) {
		if (u != par) {
			dfs(u, v);
			sz[v] += sz[u];
		}
	}
	sz[v]++;
	dp[v][0]++;
	for (auto u : gr[v]) {
		shift(u);
		rtr += ans[u] * (sz[v] - sz[u]);
		for (int fr = 0; fr < k; fr++) {
			for (int sd = 0; sd < k; sd++) {
				int sum = fr + sd, dv = sum / k, rm = (sum % k > 0);
				rtr += dp[v][fr] * dp[u][sd] * (dv + rm);
			}
		}
		for (int i = 0; i < k; i++)
			dp[v][i] += dp[u][i];
		ans[v] += ans[u];
	}
	return;
}
int main() {
	ios_base::sync_with_stdio (false), cin.tie(0), cout.tie(0);
	cin >> n >> k;
	for (int i = 0; i < n - 1; i++) {
		int x, y;
		cin >> x >> y;
		x--, y--;
		gr[x].push_back(y), gr[y].push_back(x);
	}
	dfs(0);
	cout << rtr;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll, ll>
#define pil pair<int,ll>
#define pli pair<ll,int>
#define ppi pair<pii,int>
#define pip pair<int,pii>
#define pdd pair<double, double>
#define f first
#define s second
#define MOD 1000000007
#define mkp make_pair
#define M_PI 3.14159265358979323846
#define FOR(i,l,r) for (int i=l;i<=r;i++)
#define LOR(i,l,r) for (ll i=l;i<=r;i++)
#define FORD(i,r,l) for (int i=r;i>=l;i--)
#define LORD(i,r,l) for (ll i=r;i>=l;i--)
#define INF 1000000000
#define CL(x) memset(x,0,sizeof(x))
#define DEB(x) cout << #x << " : " << x << '\n'
#define ALL(x) x.begin(), x.end()
#define SZ(x) x.size()
#define UI(x) (int)(x-'A')
#define LI(x) (int)(x-'a')
typedef long long ll;

#define MXN 200005
#define MXK 10
int N,K;
vector<int> G[MXN];
ll DP[MXN][MXK][2];//from below / tot
ll ans[MXN], tot_ans;

void dfs_ini(int u, int p=-1, int d=0)
{
    ans[1]+=(d+K-1)/K;
    DP[u][0][0]=1;
    for( int v : G[u] )if( v!=p )
    {
        dfs_ini(v,u,d+1);
        FOR(i,0,K-1)DP[u][(i+1)%K][0]+=DP[v][i][0];
    }
}

void dfs(int u, int p=-1)
{
    tot_ans+=ans[u];

    FOR(i,0,K-1)DP[u][i][1]+=DP[u][i][0];//total

    for( int v : G[u] )
    {
        if(v==p)continue;

        ans[v]=ans[u];
        FOR(i,0,K-1)
        {
            DP[v][(i+1)%K][1]=DP[u][i][1]-DP[v][(i+K-1)%K][0];
        }
        ans[v]+=( DP[u][0][1]-DP[v][K-1][0]-DP[v][0][0] );
        dfs(v,u);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin>>N>>K;
    int u, v;
    FOR(i,1,N-1)
    {
        cin>>u>>v;
        G[u].pb(v);
        G[v].pb(u);
    }
    dfs_ini(1);
    dfs(1);
    //FOR(i,1,N)FOR(j,0,K-1)cout<<i<<' '<<j<<' '<<DP[i][j][0]<<' '<<DP[i][j][1]<<'\n';
    //FOR(i,1,N)cout<<ans[i]<<'\n';
    cout<<tot_ans/2<<'\n';

    return 0;
}


#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define sz(a) ((int)a.size())
#define pb push_back
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define gmid (l + r >> 1)
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;

vector<int> G[maxn];
ll dp[maxn][5], ans;
int siz[maxn][5];
int n, k;

void dfs(int u, int f){

    siz[u][0] = 1;
    for(auto &v : G[u]){

        if(v == f) continue;
        dfs(v, u);
        for(int i = 0; i < k; ++i){

            siz[0][(i + 1) % k] = siz[v][i];
            dp[0][(i + 1) % k] = dp[v][i] + siz[v][i];
        }
        for(int i = 0; i < k; ++i){

            for(int j = 0; j < k; ++j){

                ll d1 = dp[u][i] - i * siz[u][i], d2 = dp[0][j] - j * siz[0][j];
                ans += (d1 * siz[0][j] + d2 * siz[u][i]) / k;
                int dt = (i + j + k - 1) / k;
                ans += dt * 1ll * siz[0][j] * siz[u][i];
            }
        }
        for(int i = 0; i < k; ++i){

            siz[u][i] += siz[0][i];
            dp[u][i] += dp[0][i];
        }
    }
}

int main(){

    ios::sync_with_stdio(0); cin.tie(0);
    cin >> n >> k;
    for(int i = 1; i < n; ++i){

        int u, v; cin >> u >> v;
        G[u].pb(v), G[v].pb(u);
    }
    dfs(1, 0);
    // for(int i = 1; i <= n; ++i){

    //     for(int j = 0; j < k; ++j){

    //         cout << i << " " << j << " " << siz[i][j] << " " << dp[i][j] << endl;
    //     }
    // }
    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define sz(a) ((int)a.size())
#define pb push_back
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define gmid (l + r >> 1)
const int maxn = 2e5 + 5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;

vector<int> G[maxn];
ll dp[maxn][5], ans;
int siz[maxn][5];
int n, k;

void dfs(int u, int f){

    siz[u][0] = 1;
    for(auto &v : G[u]){

        if(v == f) continue;
        dfs(v, u);
        for(int i = 0; i < k; ++i){

            siz[0][(i + 1) % k] = siz[v][i];
            dp[0][(i + 1) % k] = dp[v][i] + siz[v][i];
        }
        for(int i = 0; i < k; ++i){

            for(int j = 0; j < k; ++j){

                ll d1 = dp[u][i] - i * siz[u][i], d2 = dp[0][j] - j * siz[0][j];
                ans += (d1 * siz[0][j] + d2 * siz[u][i]) / k;
                int dt = (i + j + k - 1) / k;
                ans += dt * 1ll * siz[0][j] * siz[u][i];
            }
        }
        for(int i = 0; i < k; ++i){

            siz[u][i] += siz[0][i];
            dp[u][i] += dp[0][i];
        }
    }
}

int main(){

    ios::sync_with_stdio(0); cin.tie(0);
    cin >> n >> k;
    for(int i = 1; i < n; ++i){

        int u, v; cin >> u >> v;
        G[u].pb(v), G[v].pb(u);
    }
    dfs(1, 0);
    // for(int i = 1; i <= n; ++i){

    //     for(int j = 0; j < k; ++j){

    //         cout << i << " " << j << " " << siz[i][j] << " " << dp[i][j] << endl;
    //     }
    // }
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define eb emplace_back
#define f first
#define s second
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);

const int N=2e5+5;
bool stat[N];
vector <int> g[N];
int n,k,depth[N],par[N],ans=0;
pair <int,int> dp[N][6];

void inline input() {
	cin>>n>>k;
	for(int i=0;i<n-1;i++) {
		int x,y;
		cin>>x>>y;
		g[x].eb(y);
		g[y].eb(x);
	}
}
void dfs(int u,int p ){
	depth[u]=depth[p]+1;
	par[u]=p;
	for(auto it:g[u]) {
		if(it==p) continue;
		dfs(it,u);
		for(int j=0;j<k;j++) {
			dp[u][j].f+=dp[it][j].f;
			dp[u][j].s+=dp[it][j].s;
		}
	}
	dp[u][depth[u]%k].f++;
	dp[u][depth[u]%k].s+=depth[u];
}
void bfs() {
	memset(stat,false,sizeof(stat));
	queue <int> q;
	q.push(1);
	while(!q.empty()) {
		int u=q.front();
		stat[u]=true;
		q.pop();
		if(u==1) {
			for(int i=0;i<k;i++) {
				//cout<<dp[u][i].f<<endl;
				ans+=(dp[u][i].s)/k;
				ans-=(dp[u][i].f*i)/k;
				if(i!=0) ans+=dp[u][i].f;
			}
			//cout<<ans<<endl;
		}
		else {
			pair<int,int> tmp[k];
			for(int i=0;i<k;i++) {
				tmp[(i+1)%k].f=dp[par[u]][i].f-dp[u][(i+(depth[par[u]]%k)+k)%k].f;
				tmp[(i+1)%k].s=dp[par[u]][i].s-dp[u][(i+(depth[par[u]]%k)+k)%k].s+(dp[u][(i+(depth[par[u]]%k)+k)%k].f*depth[par[u]]);
			}

			// if(u==3) {
			// 	for(int i=0;i<k;i++) cout<<tmp[i].s<<" ";
			// }
			for(int i=0;i<k;i++) tmp[i].s+=tmp[i].f;
			for(int i=0;i<k;i++) {
				tmp[(i-(depth[u]%k)+k)%k].f+=dp[u][i].f;
				tmp[(i-(depth[u]%k)+k)%k].s+=dp[u][i].s-dp[u][i].f*depth[u];
			}
			for(int i=0;i<k;i++) {
				ans+=(tmp[i].s)/k;
				ans-=(tmp[i].f*i)/k;
				if(i!=0)ans+=tmp[i].f;
			}
			for(int i=0;i<k;i++) dp[u][i]=tmp[i];
		//	cout<<u<<" "<<ans<<endl;
		}
		for(auto it:g[u]) {
			if(!stat[it]) {
				q.push(it);
				stat[it]=true;
			}
		}
	}
}
signed main() {
	IOS
	memset(dp,0,sizeof(dp));
	input();
	depth[0]=-1;
	dfs(1,0);
	bfs();
	cout<<ans/2;
	return 0;
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2e5+10;
int dp[maxn][5],now[maxn][5],cnt[5],dep[maxn],n,m,Max[maxn];
ll sum,ans;
vector<int> G[maxn];
void dfs(int u, int fa) {
	dep[u]=dep[fa]+1;
	for (int i=0; i<G[u].size(); i++) {
		int v=G[u][i];
		if (v==fa) continue;
		dfs(v,u);
		Max[u]=max(Max[u],Max[v]+1);
		dp[u][1]+=1;
		for (int j=0; j<m; j++) dp[u][(j+1)%m]+=dp[v][j];
	}
}
void solve(int u, int fa, ll sum, vector<int> c) {
	ans+=sum;
	for (int i=0; i<G[u].size(); i++) {
		int v=G[u][i];
		if (v==fa) continue;
		vector<int> d(m,0);
		ll Sum=sum;
		for (int j=0; j<m; j++) {
			d[j]+=c[(j-1+m)%m];
			d[j]-=dp[v][(j-1+m-1)%m];
			d[j]+=dp[u][(j-1+m)%m];
			if ((j-1+m)%m==1) d[j]-=1;
		}
		Sum+=d[1%m];
		d[1%m]+=1;
		Sum-=dp[v][0];
		solve(v,u,Sum,d);
	}
}
int main() {
	scanf("%d%d",&n,&m);
	for (int i=1; i<n; i++) {
		int u,v;
		scanf("%d%d",&u,&v);
		G[u].push_back(v);
		G[v].push_back(u);
	}
	dfs(1,0);
	for (int i=1; i<=n; i++) {
		sum+=(dep[i]-1+m-1)/m;
	}
	vector<int> d(m,0);
	solve(1,0,sum,d);
	printf("%lld\n",ans/2);
	return 0;
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=2e5+10;
int dp[maxn][5],now[maxn][5],cnt[5],dep[maxn],n,m,Max[maxn];
ll sum,ans;
vector<int> G[maxn];
void dfs(int u, int fa) {
	dep[u]=dep[fa]+1;
	for (int i=0; i<G[u].size(); i++) {
		int v=G[u][i];
		if (v==fa) continue;
		dfs(v,u);
//		Max[u]=max(Max[u],Max[v]+1);
		dp[u][1%m]+=1;
		for (int j=0; j<m; j++) dp[u][(j+1)%m]+=dp[v][j];
	}
}
void solve(int u, int fa, ll sum, vector<int> c) {
	ans+=sum;
	for (int i=0; i<G[u].size(); i++) {
		int v=G[u][i];
		if (v==fa) continue;
		vector<int> d(m,0);
		ll Sum=sum;
		for (int j=0; j<m; j++) {
			d[j]+=c[(j-1+m)%m];
			d[j]-=dp[v][(j-1+m*2-1)%m];
			d[j]+=dp[u][(j-1+m)%m];
			if ((j-1+m)%m==1) d[j]-=1;
		}
		Sum+=d[1%m];
		if (m>1) d[1]+=1;
		else Sum-=1;
		Sum-=dp[v][0];
//		cout<<d[0]<<" "<<Sum<<endl;
		solve(v,u,Sum,d);
	}
}
int main() {
	scanf("%d%d",&n,&m);
	for (int i=1; i<n; i++) {
		int u,v;
		scanf("%d%d",&u,&v);
		G[u].push_back(v);
		G[v].push_back(u);
	}
	dfs(1,0);
	for (int i=1; i<=n; i++) {
		sum+=(dep[i]-1+m-1)/m;
	}
	vector<int> d(m,0);
	solve(1,0,sum,d);

	printf("%lld\n",ans/2);
	return 0;
}


import java.util.Scanner;

public class D1_690 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int R = in.nextInt();
        in.nextInt(); // C
        String row = null;
        for (int r=0; r<R; r++) {
            row = in.next();
        }
        int answer = 0;
        boolean gap = true;
        for (char c : row.toCharArray()) {
            if (c == '.') {
                gap = true;
            } else if (gap) {
                gap = false;
                answer++;
            }
        }
        System.out.println(answer);
    }

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.*;
import java.io.*;

/**
 *
 * @author root
 */
public class D1 {

    static int map[][];
    static boolean visited[][];

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String tokens[] = br.readLine().split(" ");
        int r = Integer.parseInt(tokens[0]);
        int c = Integer.parseInt(tokens[1]);
        map = new int[r][c];
        visited = new boolean[r][c];
        for (int i = 0; i < r; i++) {
            String line = br.readLine();
            for (int j = 0; j < c; j++) {
                if (line.charAt(j) == 'B') {
                    map[i][j] = 1;
                }
            }
        }
        int ans = 0;
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (!visited[i][j] && map[i][j] == 1) {
                    ans++;
                    dfs(i, j);
                }
            }
        }
        System.out.println(ans);
    }

    public static void dfs(int i, int j) {
        visited[i][j] = true;
        if (j < map[i].length - 1 && map[i][j + 1] == 1 && !visited[i][j + 1]) {
            dfs(i, j + 1);
        }

        if (j > 0 && map[i][j - 1] == 1 && !visited[i][j - 1]) {
            dfs(i, j - 1);
        }

        if (i < map.length - 1 && map[i + 1][j] == 1 && !visited[i + 1][j]) {
            dfs(i + 1, j);
        }
        if (i > 0 && map[i - 1][j] == 1 && !visited[i - 1][j]) {
            dfs(i - 1, j);
        }
    }
}


import java.io.*;
import java.util.*;

public class A {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);

		int r = s.nextInt(), c = s.nextInt(); s.nextLine();
		char[] lastRow = new char[c];
		for(int i = 0; i < r; i++) {
			if(i == r-1) {
				lastRow = s.nextLine().toCharArray();
			} else s.nextLine();
		}
		int ans = 0; boolean brick = false;
		for(int i = 0; i < c; i++) {
			char cur = lastRow[i];
			if(cur == 'B' && !brick) {
				brick = true;
				ans++;
			}
			if(cur == '.') {
				brick = false;
			}
		}
		System.out.println(ans);
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (PloadyFree@gmail.com)
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskD1 solver = new TaskD1();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD1 {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int m = in.readInt();
            boolean[] any = new boolean[m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    any[j] = in.readCharacter() == 'B' || any[j];
                }
            }
            if (ArrayUtils.count(any, true) == 0) {
                out.print(0);
                return;
            }
            int i0 = 0;
            while (!any[i0]) {
                i0++;
            }
            int i1 = m - 1;
            while (!any[i1]) {
                i1--;
            }
            i1++;
            int cnt = 0;
            while (i0 < i1) {
                cnt++;
                while (i0 < m && any[i0]) {
                    i0++;
                }
                while (i0 < m && !any[i0]) {
                    i0++;
                }
            }
            out.print(cnt);
        }

    }

    static class ArrayUtils {
        public static int count(boolean[] array, boolean value) {
            int result = 0;
            for (boolean i : array) {
                if (i == value) {
                    result++;
                }
            }
            return result;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void print(int i) {
            writer.print(i);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public char readCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.util.Scanner;

public class King {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt();
        int c = sc.nextInt();
        int k = 0;
        int l = 1;
        String s = "";
        for (int i = 0; i < r; i++) {
            s = sc.next();
        }
        if (s.charAt(0) == 'B') {
            k++;
            l = 0;
        }

        for (int j = 0; j < c; j++) {
            if (s.charAt(j) == '.')
                l++;
            if (s.charAt(j) == 'B' && l > 0) {
                k++;
                l = 0;
            }
        }
        System.out.print(k);
    }
}


import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {

	private static Set<Integer> integers;

	private static int wall[][];
	private static int R;
	private static int C;

	public static void main(String[] args) {
		integers = new HashSet<>();
		Scanner scanner = new Scanner(System.in);
		R = scanner.nextInt();
		C = scanner.nextInt();

		wall = new int[R][C];
		String line_i;
		for (int i = 0; i < R; i++) {
			line_i = scanner.next();
			for (int j = 0; j < C; j++)
				wall[i][j] = line_i.charAt(j) == 'B' ? -1 : 0;
		}
		scanner.close();

		for (int i = 0; i < R; i++)
			for (int j = 0; j < C; j++)
				markAs(i * j + j, i, j);

		System.out.println(integers.size());
	}

	private static void markAs(int mark, int i, int j) {
		if (wall[i][j] != -1)
			return;
		integers.add(mark);
		wall[i][j] = mark;
		if (i - 1 >= 0)
			markAs(mark, i - 1, j);
		if (j - 1 >= 0)
			markAs(mark, i, j - 1);
		if (i + 1 < R)
			markAs(mark, i + 1, j);
		if (j + 1 < C)
			markAs(mark, i, j + 1);
	}
}


import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Igor Kraskevich
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD1 solver = new TaskD1();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD1 {
    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        int rows = in.nextInt();
        int cols = in.nextInt();
        for (int i = 0; i < rows - 1; i++)
            in.next();
        String s = in.next();
        boolean clear = true;
        int cnt = 0;
        for (int i = 0; i < cols; i++)
            if (s.charAt(i) == 'B') {
                if (clear) {
                    clear = false;
                    cnt++;
                }
            } else {
                clear = true;
            }
        out.println(cnt);
    }
}

class FastScanner {
    private StringTokenizer tokenizer;
    private BufferedReader reader;

    public FastScanner(InputStream inputStream) {
        reader = new BufferedReader(new InputStreamReader(inputStream));
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            String line = null;
            try {
                line = reader.readLine();
            } catch (IOException e) {
                }
            if (line == null)
                return null;
            tokenizer = new StringTokenizer(line);
        }
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

}


import java.util.*;
import java.io.*;

public class D1{
    public static void main(String[] args) throws IOException{
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

	String[] line = br.readLine().split(" ");
	int r = Integer.parseInt(line[0]);
	int c = Integer.parseInt(line[1]);

	while( r-- > 1 ){
	    br.readLine();
	}

	String l = br.readLine();

	int cnt = 0;
	int i = 0;
	while( i < l.length() ){
	    if( l.charAt(i) == 'B' ){
		cnt++;
		while( i < l.length() && l.charAt(i) == 'B' )
		    i++;
	    }else{
		while( i < l.length() && l.charAt(i) == '.' )
		    i++;
	    }
	}

	out.println(cnt);

	out.close();
    }
}


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main4easy {
    public static void runBFS(boolean[][] mat, int i, int j, int H, int W){
        Queue<Par> q = new LinkedList<>();
        q.add(new Par(i, j));
        mat[i][j] = false;
        while(!q.isEmpty()){
            Par cur = q.remove();
            int ci = cur.i;
            int cj = cur.j;

            //gore
            if(ci > 0 && mat[ci-1][cj]){
                mat[ci-1][cj] = false;
                q.add(new Par(ci-1, cj));
            }

            //dole
            if(ci < (H-1) && mat[ci+1][cj]){
                mat[ci+1][cj] = false;
                q.add(new Par(ci+1, cj));
            }

            //levo
            if(cj > 0 && mat[ci][cj-1]){
                mat[ci][cj-1] = false;
                q.add(new Par(ci, cj-1));
            }

            //desno
            if(cj < (W-1) && mat[ci][cj+1]){
                mat[ci][cj+1] = false;
                q.add(new Par(ci, cj+1));
            }
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int H = sc.nextInt();
        int W = sc.nextInt();

        boolean[][] mat = new boolean[H][W]; //false by default

        for(int i = 0; i<H; i++){
            String line = sc.next();
            for(int j = 0; j<W; j++){
                if(line.charAt(j) == 'B'){
                    mat[i][j] = true;
                }
            }
        }

        int counter = 0;
        for(int i = 0; i<H; i++){
            for(int j = 0; j<W; j++){
                if(mat[i][j]){
                    counter++;
                    runBFS(mat, i, j, H, W);
                }
            }
        }
        System.out.println(counter);
    }
}

class Par{
    int i;
    int j;
    Par(int ii, int jj){
        i = ii;
        j = jj;
    }
}


#include <iostream>
#include <algorithm>

using namespace std;

const int N = 101;

int n, m;

char a[N][N];

int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

bool isValid(int x, int y){
    return x >= 0 && y >= 0 && x < n && y < m && a[x][y] == 'B';
}

void dfs(int x, int y){
    a[x][y] = '.';
    for(int i = 0; i < 4 ; i++){
        if(isValid(x + dx[i], y + dy[i]))
            dfs(x + dx[i], y + dy[i]);
    }
}

int main () {
    cin >> n >> m;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            cin >> a[i][j];
    int ans = 0;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++){
            if(a[i][j] == 'B'){
                dfs(i, j);
                ans++;
            }
        }
    cout << ans;
    return 0;
}


"use strict";

let input = readline().split(' ').map(e => +e);
let R = input[0] - 1, C = input[1];

while ( R-- > 0 )
	readline(); //ignore

let walls = readline().split('.').filter(e => e != '').length;
write(walls);


var array = readline().split(' ').map(Number);
var r = array[0];
var c = array[1];
var quantity = 0;
for (var i = 0; i < r -1; i++){
    readline();
}
var string = readline();

var flag = false;
for (var i = 0; i < string.length; i++){
    if (string[i] === 'B' && flag === false){
        flag = true;
        quantity++;
    } else if (string[i] === '.' && flag === true) {
        flag = false;
    }
}

print(quantity);


#include <iostream>
#include <cstdio>
using namespace std;
int count[200];
int main()
{
	// freopen("input.txt","r",stdin);
	// freopen("output.txt","w",stdout);
	int i,j,k=0,n,m;
	cin>>n>>m;
	// char ch='B';
	// cout<<'B'-'0'<<endl;
	string s;
	for(i=0;i<n;i++)
	{
		cin>>s;
		for (j = 0; j < m; ++j)
		{
			// cout<<s[j]<<endl;
			if(s[j]=='B')
			{
				// cout<<"yes\n";
				count[j]=1;
			}
		}
	}
	// cout<<count[0]<<endl;
	int pre=count[0];
	if(pre==1)
		k++;
	for(i=1;i<m;i++)
	{
		if(count[i]==pre)
		{
			pre=count[i];
		}
		else
		{
			if(pre==0)
				k++;
			pre=count[i];
		}

	}

	cout<<k<<endl;
	return 0;
}


#include <iostream>
#include <cstdio>
using namespace std;
int count[200];
int main(int argc, char const *argv[])
{
	// freopen("input.txt","r",stdin);
	// freopen("output.txt","w",stdout);
	int i,j,k=0,n,m;
	cin>>n>>m;
	// char ch='B';
	// cout<<'B'-'0'<<endl;
	string s;
	for(i=0;i<n;i++)
	{
		cin>>s;
		for (j = 0; j < m; ++j)
		{
			// cout<<s[j]<<endl;
			if(s[j]=='B')
			{
				// cout<<"yes\n";
				count[j]=1;
			}
		}
	}
	// cout<<count[0]<<endl;
	i=0;
	while(i<m)
	{
		// cout<<count[i]<<endl;
		while(count[i]!=1)
		{
			if(i<m)
			i++;
			else
				break;
		}
		k++;
		while(count[i]!=0&&i<m)
		{
			// cout<<"boom\n";
			if(i<m)
				i++;
			else
				break;
		}
	}
	cout<<k<<endl;
	return 0;
}


#include <iostream>
#include <cstdio>
using namespace std;
int count[200];
int main(int argc, char const *argv[])
{
	// freopen("input.txt","r",stdin);
	// freopen("output.txt","w",stdout);
	int i,j,k=0,n,m;
	cin>>n>>m;
	// char ch='B';
	// cout<<'B'-'0'<<endl;
	string s;
	for(i=0;i<n;i++)
	{
		cin>>s;
		for (j = 0; j < m; ++j)
		{
			// cout<<s[j]<<endl;
			if(s[j]=='B')
			{
				// cout<<"yes\n";
				count[j]=1;
			}
		}
	}
	// cout<<count[0]<<endl;
	for(i=0;i<m;i++)
	{
		// cout<<count[i]<<endl;
		while(count[i]!=1)
		{
			i++;
		}
		k++;
		while(count[i]!=0)
		{
			i++;
		}
	}
	cout<<k<<endl;
	return 0;
}


using namespace std;
#include<bits/stdc++.h>

#define BG begin()
#define ED end()
#define st first
#define nd second
#define PB push_back
#define PF push_front
#define FOR(i,a,b) for (long long i=a;i<b;i++)
#define FORE(i,a,b) for (long long i=a;i<=b;i++)
#define FORD(i,a,b) for (long long i=a;i>=b; i--)
#define TR(c, it) for(typeof((c).begin()) it=(c).begin(); it!=(c).end(); it++)
#define debug(x) { cout << #x << " = "; cout << (x) << endl; }
#define ri(n)({\
    int neg=0;\
    n=0;\
    char ch;\
    for(ch=getchar(); ch<'0' || ch>'9'; ch=getchar()) if (ch=='-') neg=1-neg;\
    n=ch-48;\
    for(ch=getchar(); ch>='0' && ch<='9'; ch=getchar()) n=(n<<3)+(n<<1)+ch-48;\
    if (neg) n=-n;\
})

typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> II;
typedef pair<ll,ll> LL;
typedef pair<int,II> iII;
typedef pair<II,int> IIi;
const ll INF=1000000000+7;
const double esp=1e-13;
const ld PI = acos(-1.0);

ll nhan(ll x, ll y, ll m){
    ll ans=0;
    while (y){
        if (y%2) ans=(ans+x)%m;
        x=x*2%m;
        y/=2;
    }
    return ans;
}

ll power(ll a, ll n, ll m){
    ull ans=1;
    while (n){
        if (n%2) ans=ans*a%m;
        a=a*a%m;
        n/=2;
    }
    return ans;
}

bool check(ll n){
    if (n==2) return true;
    if (n<2 || n%2==0) return false;
    ll p[3]={3,5,7};
    ll a,d;
    int r,s;
    d=n-1;
    s=0;
    while (d%2==0){
        d/=2;
        s++;
    }
    FORE(i,0,2){
        if (n==p[i]) return true;
        if (n%p[i]==0) return false;
        a=power(p[i],d,n);
        if (a!=1){
            for (r=0; r<s && a!=n-1; r++) a=a*a%n;
            if (r==s) return false;
        }
    }
    return true;
}

ll phi(ll n){
    ll ans=n;
    ll n2=(ll)sqrt(n);
    FORE(i,2,n2)
    if (n%i==0){
        while (n%i==0) n/=i;
        ans-=ans/i;
    }
    if (n>1) ans-=ans/n;
    return ans;
}

int xx[] = {0,0,1,-1};
int yy[] = {1,-1,0,0};

string s;
int n,m,a[200][200], ans;
bool f[200][200];

void dfs(int x, int y){
    f[x][y]=0;
    FORE(k,0,3){
        int xxx = x+xx[k];
        int yyy = y+yy[k];
        if (xxx>0 && xxx<=n && yyy>0 && yyy<=m && f[xxx][yyy] && a[xxx][yyy]) dfs(xxx,yyy);
    }
}

int main(){
 //   freopen("codeforces.inp", "r", stdin);
 //   freopen(".out", "w", stdout);
    ios_base::sync_with_stdio (false);
    cin.tie();
  //  srand(time(0));
    cin >> n >> m;
    FORE(i,1,n){
        cin >> s;
        FOR(j,0,m)
        if (s[j]=='B') a[i][j+1] = 1;
        else a[i][j+1] = 0;
    }
    memset(f,true,sizeof(f));
    FORE(i,1,n)
    FORE(j,1,m)
    if (a[i][j] && f[i][j]){
        ans++;
        dfs(i,j);
    }
    cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define MOD 1000000007
#define Oo 1000000000
#define EPS 1e-9
#define PI acos(-1)

typedef pair <int, int> ii;
typedef vector <ii> vii;
typedef vector <int> vi;
typedef long long ll;
typedef unsigned long long ull;
typedef pair <ll, ll> pll;

int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
int dx2[] = {1,-1,-1,1,0,0,-1,1};
int dy2[] = {1,-1,1,-1,1,-1,0,0};
int kmx[] = {-1, -1, 1, 1, 2, -2, 2, -2};
int kmy[] = {2, -2, 2, -2, -1, -1, 1, 1};

class Timer
{
public:
    clock_t T;
    Timer()
    {
        T = clock();
    }
    ~Timer()
    {
        fprintf(stderr, "\n%.3f\n", double(clock()-T)/CLOCKS_PER_SEC);
    }
};

int read()
{
    int x;
    scanf("%d", &x);
    return x;
}
ll readL()
{
    ll x;
    scanf("%lld", &x);
    return x;
}
const int N = 105;
int n, m;
char s[N][N];
int vis[N][N];
void floodFill(int x, int y) {
    int nx, ny;
    vis[x][y] = 1;
    for(int i=0;i<4;i++) {
        nx = x + dx[i];
        ny = y + dy[i];
        if(nx==-1||ny==-1||nx==n||ny==m||vis[nx][ny]||s[nx][ny]!='B')
            continue;
        floodFill(nx, ny);
    }
}

int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt", "r", stdin);
        Timer timer;
    #endif // ONLINE_JUDGE

    n = read();
    m = read();
    for(int i=0;i<n;i++) {
        scanf("%s", s);
    }
    int cnt = 0;
    for(int i=0;i<n;i++) {
        for(int j=0;j<m;j++) {
            if(!vis[i][j] && s[i][j] == 'B') {
                cnt++;
                floodFill(i, j);
            }
        }
    }
    printf("%d\n", cnt);

    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
char a[111][111];
int h[111];
int main()
{
	int r,c;
	scanf("%d%d",&r,&c);
	for(int i=0;i<r;i++)scanf("%s",a[i]+1);
	for(int i=1;i<=c;i++)
    {
        for(int j=0;j<r;j++){
            if(a[j][i]=='B'){
                h[i]=r-j;
                break;
            }
        }
    }
    int m=0;
    for(int i=1;i<=c;i++){
        if(!h[i]&&h[i-1])m++;
    }
    if(h[c])m++;
    printf("%d\n",m);
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
char a[111][111];
int h[111];
int main()
{
	int r,c;
	scanf("%d%d",&r,&c);
	for(int i=0;i<r;i++)scanf("%s",a[i]);
	for(int i=0;i<c;i++)
    {
        for(int j=0;j<r;j++){
            if(a[j][i]=='B'){
                h[i]=r-j;
                break;
            }
        }
    }
    int m=0;
    if(h[0]&&!h[1])m++;
    for(int i=1;i<=c;i++){
        if(!h[i]&&h[i-1])m++;
    }
    printf("%d\n",m);
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
char a[111][111];
int h[111];
int main()
{
	int r,c;
	scanf("%d%d",&r,&c);
	for(int i=0;i<r;i++)scanf("%s",a[i]);
	for(int i=0;i<c;i++)
    {
        for(int j=0;j<r;j++){
            if(a[j][i]=='B'){
                h[i]=r-j;
                break;
            }
        }
    }
    int m=0;
    if(h[0]&&!h[1])m++;
    for(int i=1;i<c;i++){
        if(!h[i]&&i>0&&h[i-1])m++;
        if(i==c-1&&h[i])m++;
    }
    printf("%d\n",m);
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
char a[111][111];
int h[111];
int main()
{
	int r,c;
	scanf("%d%d",&r,&c);
	for(int i=0;i<r;i++)scanf("%s",a[i]);
	for(int i=0;i<c;i++)
    {
        for(int j=0;j<r;j++){
            if(a[j][i]=='B'){
                h[i]=r-j;
                break;
            }
        }
    }
    int m=0;
    for(int i=1;i<c;i++){
        if(!h[i]&&h[i-1])m++;
        if(i==c-1&&h[i])m++;
    }
    printf("%d\n",m);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int r,c,total;
char wall[100];

int main()
{
    cin>>r>>c;
    for(int i=0;i<r-1;i++)
        for(int j=0;j<c;j++)
        cin>>wall[0];
    cin>>wall[0];
    if(wall[0]=='B')
        total++;
    for(int i=1;i<c;i++)
    {
        cin>>wall[i];
        if(wall[i-1]=='.'&&wall[i]=='B')
            total++;
    }
    cout<<total<<endl;
}


#include<iostream>
using namespace std;

int main()
{
    int rows,columns,i,j,cnt=0;

    cin>>rows;
    cin>>columns;

    char matrix[rows][columns];

    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            cin>>matrix[i][j];
        }
        cout<<endl;
    }

    for(i=0;i<(columns);i++)
    {
        if(matrix[rows-1][i]=='B')
        cnt++;
    }
    for(i=0;i<(columns-1);i++)
    {
        if(matrix[(rows-1)][i]=='B'&&matrix[(rows-1)][i+1]=='B')
        cnt--;
    }
    cout<<cnt;
    return 0;
}


#include<iostream>
using namespace std;

int main()
{
    int rows,columns,i,j,cnt=0;

    cin>>rows;
    cin>>columns;

    char matrix[rows][columns];

    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            cin>>matrix[i][j];
        }
        cout<<endl;
    }

    for(i=0;i<(columns-1);i++)
    {
        if(matrix[rows-1][i]=='B')
        cnt++;
    }
    for(i=0;i<(columns-1);i++)
    {
        if(matrix[rows-1][i]=='B'&&matrix[rows-1][i+1]=='B')
        cnt--;
    }
    cout<<cnt;
    return 0;
}

1


#include<iostream>
using namespace std;

int main()
{
    int rows,columns,i,j,cnt=0;

    cin>>rows;
    cin>>columns;

    char matrix[rows][columns];

    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            cin>>matrix[i][j];
        }
        cout<<endl;
    }

    for(i=0;i<columns;i++)
    {
        if(matrix[rows][i]=='B')
        cnt++;
    }
    for(i=0;i<(columns-1);i++)
    {
        if(matrix[rows][i]=='B'&&matrix[rows][i+1]=='B')
        cnt--;
    }
    cout<<cnt;
    return 0;
}


#include<iostream>
using namespace std;
int main()
{
    int rows,columns,i,j,cnt=0;

    cin>>rows;
    cin>>columns;

    char matrix[rows][columns];

    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            cin>>matrix[i][j];
        }
        cout<<endl;
    }

    for(i=0;i<columns;i++)
    {
        if(matrix[rows][i]=='B')
        cnt++;
    }
    for(i=0;i<columns;i++)
    {
        if(matrix[rows][i]=='B'&&matrix[rows][i+1]=='B')
        cnt--;
    }
    cout<<cnt;
    return 0;
}


#include<iostream>
using namespace std;

int main()
{
    int rows,columns,i,j,cnt=0;

    cin>>rows;
    cin>>columns;

    char matrix[rows][columns];

    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            cin>>matrix[i][j];
        }
        cout<<endl;
    }

    for(i=0;i<(columns-1);i++)
    {
        if(matrix[rows-1][i]=='B')
        cnt++;
    }
    for(i=0;i<(columns-1);i++)
    {
        if(matrix[(rows-1)][i]=='B'&&matrix[(rows-1)][i+1]=='B')
        cnt--;
    }
    cout<<cnt;
    return 0;
}


#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath>
using namespace std;
#define fr first
#define sc second
#define cl clear
#define BUG puts("here!!!")
#define W(a) while(a--)
#define pb(a) push_back(a)
#define Rint(a) scanf("%d", &a)
#define Rll(a) scanf("%I64d", &a)
#define Rs(a) scanf("%s", a)
#define Cin(a) cin >> a
#define FRead() freopen("in", "r", stdin)
#define FWrite() freopen("out", "w", stdout)
#define Rep(i, len) for(int i = 0; i < (len); i++)
#define For(i, a, len) for(int i = (a); i < (len); i++)
#define Cls(a) memset((a), 0, sizeof(a))
#define Clr(a, x) memset((a), (x), sizeof(a))
#define Full(a) memset((a), 0x7f7f7f, sizeof(a))
#define lrt rt << 1
#define rrt rt << 1 | 1
#define pi 3.14159265359
#define RT return
#define lowbit(x) x & (-x)
#define onecnt(x) __builtin_popcount(x)
typedef long long LL;
typedef long double LD;
typedef unsigned long long ULL;
typedef pair<int, int> pii;
typedef pair<string, int> psi;
typedef pair<int, int> pll;
typedef map<string, int> msi;
typedef vector<int> vi;
typedef vector<int> vl;
typedef vector<vl> vvl;
typedef vector<bool> vb;

const int maxn = 110;
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};

int n, m, ret;
char G[maxn][maxn];

bool ok(int x, int y) {
	return x>=0&&y>=0&&x<n&&y<m;
}
void dfs(int x, int y) {
	if(G[x][y] =='.') return;
	G[x][y] = '.';
	Rep(i, 4) {
		int tx = x + dx[i];
		int ty = y + dy[i];
		if(ok(tx, ty) && G[tx][ty] == 'B') {
			dfs(tx, ty);
		}
	}
}

signed main() {
	// FRead();
	while(~Rint(n) && ~Rint(m)) {
		Cls(G); ret = 0;
		Rep(i, n) Rs(G[i]);
		Rep(i, n) {
			Rep(j, m) {
				if(G[i][j] == 'B') {
					dfs(i, j);
					ret++;
				}
			}
		}
		printf("%d\n", ret);
	}
	RT 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
	int n,m; scanf("%d %d", &n, &m);
	char t[n+2][m+2];
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
			scanf(" %c", &t[i][j]);
	int ans=0;
	for(int i=0;i<m;i++){
		if(t[n-1][i] == 'B'){
			ans++;
			while(i<m && t[n-1][i] != '.') i++;
		}
	}
	printf("%d", ans);

}


#include<iostream>
using namespace std;
int main(){
	int n,m; scanf("%d %d", &n, &m);
	char t[n+2][m+2];
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
			scanf(" %c", &t[i][j]);
	int ans=0;
	for(int i=0;i<m;i++){
		if(t[n-1][i] == 'B'){
			ans++;
			while(i<m && t[n-1][i] != '.')i++;
		}
	}
	printf("%d", ans);

}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int tu[102][102], ans = 0, n, m, vis[102][102], bx[5], by[5];

void dfs(int x, int y){
	vis[x][y] = 1;
	for(int k = 1; k <= 4; k++){
		int i = x + bx[k], j = y + by[k];
		if(tu[i][j] && vis[i][j] == 0) dfs(i, j);
	}
}

int main(){
	cin >> n >> m;
	char a;
	bx[1] = 1, bx[2] = 0, bx[3] = -1, bx[4] = 0;
	by[1] = 0, by[2] = 1, by[3] = 0, by[4] = -1;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++){
			cin >> a;
			if(a == 'B') tu[i][j] = 1;
			else tu[i][j] = 0;
		}
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++)
			if(!vis[i][j] && tu[i][j]) dfs(i, j), ans++;
	printf("%d", ans);
	return 0;
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int tu[102][102], ans = 0, n, m;

int main(){
	cin >> n >> m;
	char a;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++){
			cin >> a;
			if(a == 'B') tu[i][j] = 1;
			else tu[i][j] = 0;
		}
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++)
			if(tu[i][j])
				if(!tu[i - 1][j] && !tu[i][j - 1]) ans++;
	printf("%d", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef pair<int, int> II;

const int N = 100 + 10;
int n, m;
char S[N];

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; ++i) scanf("%s", S + 1);

	int ans = 0;
	for (int i = 1; i <= m; ++i) if (S[i] == 'B') {
		int j = i;
		while (j < m && S[j + 1] == 'B') j++;
		i = j; ans++;
	}
	printf("%d", ans);
	return 0;
}


#include <vector>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sstream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <ctime>
#include <cassert>

using namespace std;

char wall[101][101];
int marked[101][101];

void Dfs(int i, int j, int n, int m) {
    marked[i][j] = 1;
    int dir[4][2] = {{-1,0}, {0,-1}, {1,0}, {0, 1}};
    for(int d = 0; d < 4; ++d) {
        int xi = i + dir[d][0];
        int yi = j + dir[d][1];
        if (xi >= 0 && xi < n && yi >= 0 && yi < m) {
            if (marked[xi][yi] == 0 && wall[xi][yi] == 'B') {
                Dfs(xi, yi, n, m);
            }
        }
    }
}

int Count(int n, int m) {
    memset(marked, 0, sizeof(marked));
    int count = 0;
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < m; ++j) {
            if (marked[i][j] == 0 && wall[i][j] == 'B') {
                Dfs(i, j, n, m);
                count++;
            }
        }
    }
    return count;
}

void InputAndSolve(int n, int m) {
    for(int i = 0; i < n; ++i) {
        scanf("%s", wall[i]);
    }
    printf("%d\n", Count(n, m));
}

int main() {
    int n, m;
    while(scanf("%d%d",&n,&m) != EOF) {
        InputAndSolve(n, m);
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int r,c,res=0;
char a[101];
int main() {
    //FILE *f=freopen("input.txt","rt",stdin);
    scanf("%d%d%*c",&r,&c);
    a[0]='.';
    for (int i=1;i<=r;i++) {
        for (int j=1;j<=c;j++) {
            scanf("%c",&a[j]);
            if (i==r && a[j]=='B' && a[j-1]!='B') res++;
        }
        scanf("%*c");
    }
    printf("%d",res);
    return 0;
}


#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <utility>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <climits>
#include <fstream>
#include <ctime>
using namespace std;

int r,c,ans;
bool cont;
char s[109];

int main(){
    scanf("%d %d",&r,&c);
    for(int i=0;i<r;i++) scanf("%s",s);
    for(int i=0;i<c;i++){
        if(s[i]=='B'&&cont==0){
            ans++;
            cont++;
        }
        else if(s[i]=='.') cont=0;
    }
    printf("%d",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int n,m,ans;
char a[505][505];

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            cin>>a[i][j];
    a[n][0]='.';
    for(int i=1;i<=m;i++)
        if(a[n][i]=='B' && a[n][i-1]=='.')
            ++ans;
    cout<<ans<<"\n";
}


#include<cstdio>
#include<cstring>
char map[110][110];
bool vis[110][110];
int n,m;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
void dfs(int x,int y)
{
     if(x < 0 || x >= n || y < 0 || y >= m || map[x][y] != 'B' || vis[x][y])
        return;//
    vis[x][y] = true;
    for(int i = 0; i < 4 ; i++)
    {
        int xx = x + dx[i];
        int yy = y + dy[i];
        dfs(xx,yy);
    }
}
int main()
{
    int cnt = 0;
    scanf("%d%d",&n,&m);
    for(int i = 0 ; i < n ; i++)
        scanf("%s",map[i]);
    memset(vis,false,sizeof(vis));
    for(int i = 0 ; i < n ; i++)
        for(int j = 0 ; j < m ; j++)
    {
        if(map[i][j] == 'B' && !vis[i][j])
        {
            dfs(i,j);
            cnt++;
        }
    }
    printf("%d\n",cnt);
    return 0;
}


#include<stdio.h>
#include<algorithm>
#include<queue>
#include<vector>
#include<iostream>
#define M 105
using namespace std;
int tot=0;
char mp[M][M];
bool mark[M][M];
int rx[]={-1,1,0,0};
int ry[]={0,0,-1,1},n,m;
void dfs(int x,int y){
	mark[x][y]=1;
	for(int i=0;i<4;i++){
		if((mp[x+rx[i]][y+ry[i]]=='B')&&(mark[x+rx[i]][y+ry[i]]==0))dfs(x+rx[i],y+ry[i]);
	}
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%s",mp[i]+1);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			if(mp[i][j]=='B'&&mark[i][j]==0){
				tot++;dfs(i,j);
			}
	printf("%d\n",tot);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    int r,c,i,count=0;
    cin>>r>>c;
    while(r--)
        cin>>s;
    for(i=0;i<c;i++)
    {
        if(i==0)
        {
            if(s[i]=='B')
                count++;
        }
        else {
            if(s[i]=='B' and s[i-1]=='.')
                count++;
        }
    }
    cout<<count;
}


#include<bits/stdc++.h>

using namespace std;

int main()
{
    int n,m,i,j,cnt=0,st,en,ans=0;

    char s[105][105];

    cin>>n>>m;

    for(i=0; i<n; i++)
    {
        for(j=0; j<m; j++)
        {
            cin>>s[i][j];
        }
    }

    for(j=0; j<m; j++)
    {
        if(s[n-1][j]=='B')
        {
            cnt++;

            en=j;
        }

        else if(s[n-1][j]=='.')
        {
            if(cnt>0)
            {
                ans++;
            }

            cnt=0;
        }
    }

    if(en==m-1) ans++;

    cout<<ans<<endl;

}


#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <assert.h>
#define FREAD(fn) freopen((fn), "r", stdin)
#define RINT(vn) scanf("%d", &(vn))
#define PINT(vb) printf("%d", vb)
#define RSTR(vn) scanf("%s", (vn))
#define PSTR(vn) printf("%s", (vn))
#define CLEAR(A, X) memset(A, X, sizeof(A))
#define REP(N) for(int i=0; i<(N); i++)
#define REPE(N) for(int i=1; i<=(N); i++)
#define pb(X) push_back(X)
#define pn() printf("\n")
using namespace std;
const int MAX_N = 105;
//不要把i,j设成全局量

char M[MAX_N][MAX_N];
int r, c;
int dx[]={0, 0, 1, -1}, dy[]={1, -1, 0, 0};
bool vis[MAX_N][MAX_N];

bool out(int x, int y){
	if(x<0 || y<0 || x>=r || y>=c) return true;
	return false;
}

void dfs(int x, int y){
	vis[x][y] = 1;
	REP(4){
		int nx = x+dx[i];
		int ny = y+dy[i];
		if(out(nx, ny)) continue;
		if(vis[nx][ny]) continue;
		if(M[nx][ny] == 'B') dfs(nx, ny);
	}
}

int main()
{
	//FREAD("690d1.txt");
	CLEAR(vis, 0);
	RINT(r); RINT(c);
	REP(r){
		getchar();
		RSTR(M[i]);
	}
	int cnt = 0;
	REP(r){
		for(int j=0; j<c; j++){
			if(M[i][j] == 'B' && !vis[i][j]){
				dfs(i, j);
				cnt++;
			}
		}
	}
	PINT(cnt);
	return 0;
}


#include <iostream>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(0);
	int n, m;
	cin >> n >> m;
	char prev = '.';
	int ans = 0;
	char c;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> c;
			if (i != n - 1) continue;
			if (j == 0) continue;
			if (c == '.' and prev == 'B') ans++;
			prev = c;
		}
	}
	if (c == 'B') ans++;
	cout << ans << "\n";

	return 0;
}


#include <iostream>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(0);
	int n, m;
	cin >> n >> m;
	char prev = '.';
	int ans = 0;
	char c;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> c;
			if (i != n - 1) continue;
			if (j == 0)
			{
				prev = c;
				continue;
			}
			if (c == '.' and prev == 'B') ans++;
			prev = c;
		}
	}
	if (c == 'B') ans++;
	cout << ans << "\n";

	return 0;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef long double ldb;

#define fi first
#define se second
#define pb push_back
#define mkp make_pair
#define all(v) (v).begin(),(v).end()
#define dbg(a) cout << #a << " = " << a << endl

int n,m;
char d[101][101];
int used[101][101];

void dfs(int y, int x) {
	used[y][x] = 1;
	if(y - 1 >= 0 && !used[y-1][x]) {
		dfs(y-1, x);
	}
	if(y + 1 < n && !used[y+1][x]) {
		dfs(y+1, x);
	}
	if(x - 1 >= 0 && !used[y][x-1]) {
		dfs(y, x-1);
	}
	if(x + 1 < m && !used[y][x+1]) {
		dfs(y, x + 1);
	}
}

int main() {

	ios_base::sync_with_stdio(false);
    cin.tie(0);

	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);

	cin >> n >> m;
	for(int i = 0; i < n; i++) {
		for(int j = 0; j < m; j++) {
			cin >> d[i][j];
			if(d[i][j] == '.') {
				used[i][j] = 1;
			}
			else {
				used[i][j] = 0;
			}
		}
	}

	int ans = 0;
	for(int i = 0; i < n; i++) {
		for(int j = 0; j < m; j++) {
			if(!used[i][j]) {
				dfs(i, j);
				ans++;
			}
		}
	}
	cout << ans;

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define N 1010
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
char s[N][N];
int n,m;
void dfs(int x,int y){
	s[x][y]='.';
	for(int i=0;i<4;i++){
		int xx=x+dx[i];
		int yy=y+dy[i];
		if(xx<n&&xx>=0&&yy<m&&yy>=0&&s[xx][yy]=='B') dfs(xx,yy);
	}
}
int main(){
	//freopen("tmp.txt","r",stdin);
	int a,b;
	while(~scanf("%d%d",&n,&m)){
		for(int i=0;i<n;i++){
			scanf("%s",s[i]);
		}
		int ans=0;
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				if(s[i][j]=='B'){
					dfs(i,j);
					ans++;
				}
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define N 1010
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
char s[N][N];
int n,m;
void dfs(int x,int y){
	s[x][y]='.';
	for(int i=0;i<4;i++){
		int xx=x+dx[i];
		int yy=y+dy[i];
		if(xx<n&&xx>=0&&yy<m&&yy>=0&&s[xx][yy]=='B') dfs(xx,yy);
	}
}
int main(){
	freopen("tmp.txt","r",stdin);
	int a,b;
	while(~scanf("%d%d",&n,&m)){
		for(int i=0;i<n;i++){
			scanf("%s",s[i]);
		}
		int ans=0;
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				if(s[i][j]=='B'){
					dfs(i,j);
					ans++;
				}
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int N = 110;
int n,m,p;
char d[N][N];
int num[N][N];
int fa[N*N];
int find(int a)
{
	if(fa[a]==a) return a;
	return fa[a] = find(fa[a]);
}
int main()
{
	int tot = 0;
	scanf("%d%d",&n,&m);
	for(int i = 1; i <= n; i ++) scanf("%s",&d[i][1]);

	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++)
			num[i][j] = ++p,fa[p]=p;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++)
		{
			if(d[i][j] == 'B')
			{
				if(d[i][j+1]=='B') fa[num[i][j]] = find(num[i][j+1]);
				if(d[i+1][j]=='B') fa[num[i][j]] = find(num[i+1][j]);
			}
			else tot ++;
		}
	int ans = 0;
	for(int i = 1; i <= p; i++) ans += (fa[i] == i);
	printf("%d\n",ans - tot);
	return 0;
}


#include <iostream>
#include<cstring>
using namespace std;

int main() {
	int i,j,r,c;
	cin>>r>>c;
	char b[r][c];
	for(i=0;i<r;i++){
		for(j=0;j<c;j++){
		cin>>b[i][j];
	}
}
	int p=1;
	for(j=1;j<c-1;j++){
		if(b[r-1][j]=='.'&&b[r-1][j-1]=='B'&&b[r-1][j+1]=='B')
		p++;
	}
	cout<<p<<"\n";

	return 0;
}


#include <iostream>
#include<cstring>
using namespace std;

int main() {
	int i,j,r,c;
	cin>>r>>c;
	char b[r][c];
	for(i=0;i<r;i++){
		for(j=0;j<c;j++){
		cin>>b[i][j];
	}
}
	int p=0;
	if(b[r-1][0]=='B')
	p=1;
	for(j=1;j<c;j++){

		if(b[r-1][j]=='B'&&b[r-1][j-1]=='.')
		p++;
	}
	cout<<p<<"\n";

	return 0;
}


/*
  ------------------------- Hachiikung ---------------------------------
  ---------------------- Worrachate Bosri ------------------------------
  ------ Faculty of Computer Engineering Chulalongkorn University ------
*/
#include <bits/stdc++.h>
using namespace std;
#define REP(i,FN) for(int i=0;i<FN;i++)
#define FOR(i,ST,FN) for(int i=ST;i<=FN;i++)
#define FORD(i,FN,ST) for(int i=FN;i>=ST;i--)
#define FORX(i,c) for(typeof(c.begin())i=c.begin();i!=c.end();i++)
#define pause system("pause")
#define S scanf
#define P printf
#define X first
#define Y second
#define pb push_back
#define PII pair<int,int>
#define mp make_pair
#define sz size()
#define eps 1e-8

const int MOD(1000000007);
const int INF((1<<30)-1);
const int MAXN(105);

int n, m, d[4][2] = {1,0,-1,0,0,1,0,-1};

char a[MAXN][MAXN];

bool visited[MAXN][MAXN];

void dfs(int x,int y){

    visited[x][y] = 1;

    REP(k,4)
    {
        int tx = x + d[k][0];
        int ty = y + d[k][1];
        if(tx >= 0 && tx < n && ty >= 0 && ty < m && a[tx][ty] == 'B' && !visited[tx][ty])
            dfs(tx,ty);
    }

}

int main(){

    S("%d%d",&n,&m);
    REP(i,n)
        S("%s",a[i]);

    int ans = 0;

    REP(i,n)
        REP(j,m)
        {
            if(a[i][j] == 'B' && !visited[i][j])
            {
                dfs(i,j);
                ans++;
            }
        }

    P("%d",ans);

}


#include<iostream>
#include<stdio.h>
#include<vector>
#include<string>
#include<set>
#include<algorithm>
#include<memory.h>
using namespace std;

	int dx[]={0 , 0 , 1 , 1 , 1 ,-1 ,-1 ,-1};
	int dy[]={1 ,-1 , 0 , 1 ,-1 , 0 , 1 ,-1};
	char ar[150][150];
	bool vis[150][150];
	int n , m ;

	void dfs (int x , int y)
	{
		vis[x][y]=true;

		for (int i =0 ; i<8 ;++i)
		{
			int tx=dx[i]+x;
			int ty=dy[i]+y;

			if (!vis[tx][ty] && tx<n && ty<m && tx>=0 && ty>=0 && ar[tx][ty]=='B') dfs(tx,ty);

			}

		}

int main()
{

	//freopen("in.txt","r",stdin);

	scanf("%d%d",&n,&m);
	memset(vis,0,sizeof(vis));
	for (int i=0 ; i<n ;++i)
	for (int j=0 ; j<m ; ++j)
		cin>>ar[i][j];

	int count=0;
	for (int i=0 ; i<n ; ++i)
	for (int j=0 ; j<m ; ++j)
		if ( !vis[i][j] && ar[i][j]=='B') {dfs(i,j); count++;}

	printf("%d\n",count);
return 0; }


#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;
int main ()
{
	int r,c;

cin>>r>>c;
	string *str = new string[r];
for(int i=0;i<r;i++)
{
cin>>str[i];

}

int counter=0;

bool wall_exist=false;
for(int p=0;p<c;p++)
{
if(str[r-1].at(p)=='.'&&wall_exist) {
counter++;
wall_exist=false;
}

if(str[r-1].at(p)=='B') wall_exist=true;

}
if(wall_exist ) counter++;

cout<<counter;
return 0;
}


#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;
int main ()
{
	int r,c;

cin>>r>>c;
	string *str = new string[r];
for(int i=0;i<r;i++)
{
cin>>str[i];

}

int counter=0;

bool wall_exist=false;
for(int p=0;p<c;p++)
{
if(str[r-1].at(p)=='.'&&wall_exist) counter++;
if(str[r-1].at(p)=='B') wall_exist=true;

}
if(wall_exist ) counter++;
//cout<<"check: "<<str[r-1];
cout<<counter;
return 0;
}