Problem:
Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
#define FRU freopen("out.txt","w",stdout)
#define FRO freopen("in.txt","r",stdin)
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define mem(ara,n) memset(ara,n,sizeof ara)
#define loop(i,j,n) for(i=j;i<n;i++)
#define rloop(i,j,n) for(i=n;i>=j;i--)
#define INF 2147483647
#define ll long long
#define pii pair<int,int>
#define eps 1e-9
#define mii map<int,int>
#define vi vector<int>
#define all(n) n.begin(),n.end()
#define inf INF
#define INFLL 10000000000000000LL
using namespace std;
const int row[]={-1,0,0,1};
const int col[]={0,-1,1,0};

int N,M,a,b,c;
ll cnt;
char s[401][401];
int grid[401][401];
int vis[401][401];

void f(int x,int y)
{
    vis[x][y]=c;
    if(grid[x][y]==0)a++,cnt+=(ll)b;
    else b++,cnt+=(ll)a;
    for(int i=0;i<4;i++)
    {
        int xx=x+row[i];
        int yy=y+col[i];
        if(xx>=0&& xx<N&& yy>=0&& yy<M&& grid[xx][yy]!=grid[x][y]&& vis[xx][yy]==0)
        {
            f(xx,yy);
        }
    }
}

int main()
{
    int n,m,i,j,k,tc,t;
    cin>>n>>m;
    N=n,M=m;
    for(i=0;i<n;i++)
    {
        cin>>s[i];
        for(j=0;j<m;j++)grid[i][j]=s[i][j]=='.'?0:1;
    }
    int ans=0;
    for(i=0;i<n;i++)
    {
        for(j=0;j<M;j++)
        {
            if(vis[i][j]==0)
            {
                a=b=0;
                c++;
                f(i,j);
                //ans+=(a*b);
            }
        }
    }
    /*for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)printf("%d ",vis[i][j]);printf("\n");
    }*/
    cout<<cnt<<endl;//cout<<c<<endl;
}