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# (.NET Core 3.1.201) (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Xml.Schema;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using System.IO.Pipes;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.CodeDom;
using System.Diagnostics.SymbolStore;
using System.Dynamic;

namespace AtCoder
{
    public static class Ex
    {
        public static List<string> FastSort(this List<string> s) { s.Sort(StringComparer.OrdinalIgnoreCase); return s.ToList(); }
        public static void yesno(this bool b) { Console.WriteLine(b ? "yes" : "no"); }
        public static void YesNo(this bool b) { Console.WriteLine(b ? "Yes" : "No"); }
        public static void YESNO(this bool b) { Console.WriteLine(b ? "YES" : "NO"); }

        public static int PopCount(this int bits)
        {
            bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
            bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
            bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
            bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
            return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff);
        }
    }

    partial class AtCoder
    {
        public string GetStr() { return Console.ReadLine().Trim(); }
        public char GetChar() { return Console.ReadLine().Trim()[0]; }
        public int GetInt() { return int.Parse(Console.ReadLine().Trim()); }
        public long GetLong() { return long.Parse(Console.ReadLine().Trim()); }
        public double GetDouble() { return double.Parse(Console.ReadLine().Trim()); }
        public string[] GetStrArray() { return Console.ReadLine().Trim().Split(' '); }
        public int[] GetIntArray() { return Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray(); }
        public long[] GetLongArray() { return Console.ReadLine().Trim().Split(' ').Select(long.Parse).ToArray(); }
        public char[] GetCharArray() { return Console.ReadLine().Trim().Split(' ').Select(char.Parse).ToArray(); }
        public double[] GetDoubleArray() { return Console.ReadLine().Trim().Split(' ').Select(double.Parse).ToArray(); }
        public T[][] CreateJaggedArray<T>(int H, int W, T value) { return Enumerable.Repeat(0, H).Select(s => Enumerable.Repeat(value, W).ToArray()).ToArray(); }
        public int[][] GetIntJaggedArray(int N) { return Enumerable.Repeat(0, N).Select(s => GetIntArray().ToArray()).ToArray(); }
        public long[][] GetLongJaggedArray(int N) { return Enumerable.Repeat(0, N).Select(s => GetLongArray().ToArray()).ToArray(); }
        public char[][] GetCharJaggedArray(int N) { return Enumerable.Repeat(0, N).Select(s => GetStr().ToCharArray()).ToArray(); }
        public double[][] GetDoubleJaggedArray(int N) { return Enumerable.Repeat(0, N).Select(s => GetDoubleArray()).ToArray(); }

        Dictionary<int, List<int>> GetUnweightedAdjacencyList(int N, int M, bool isDirected, bool isNode_0indexed)
        {
            var dic = new Dictionary<int, List<int>>();
            foreach (var e in Enumerable.Range(0, N)) { dic.Add(e, new List<int>()); }
            for (int i = 0; i < M; i++)
            {
                var input = GetIntArray();
                var a = isNode_0indexed ? input[0] : input[0] - 1;
                var b = isNode_0indexed ? input[1] : input[1] - 1;
                dic[a].Add(b);
                if (isDirected == false) dic[b].Add(a);
            }
            return dic;
        }
        Dictionary<int, List<Edge>> GetWeightedAdjacencyList(int N, int M, bool isDirected, bool isNode_0indexed)
        {
            var dic = new Dictionary<int, List<Edge>>();
            foreach (var e in Enumerable.Range(0, N)) { dic.Add(e, new List<Edge>()); }
            for (int i = 0; i < M; i++)
            {
                var input = GetIntArray();
                var a = isNode_0indexed ? input[0] : input[0] - 1;
                var b = isNode_0indexed ? input[1] : input[1] - 1;
                var c = input[2];
                dic[a].Add(new Edge(b, c));
                if (isDirected == false) dic[b].Add(new Edge(a, c));
            }
            return dic;
        }

        bool eq<T, U>() => typeof(T).Equals(typeof(U));
        T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
        T cv<T>(string s) => eq<T, int>() ? ct<T, int>(int.Parse(s))
                           : eq<T, long>() ? ct<T, long>(long.Parse(s))
                           : eq<T, double>() ? ct<T, double>(double.Parse(s))
                           : eq<T, char>() ? ct<T, char>(s[0])
                                             : ct<T, string>(s);
        void Multi<T>(out T a) => a = cv<T>(GetStr());
        void Multi<T, U>(out T a, out U b)
        {
            var ar = GetStrArray(); a = cv<T>(ar[0]); b = cv<U>(ar[1]);
        }
        void Multi<T, U, V>(out T a, out U b, out V c)
        {
            var ar = GetStrArray(); a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]);
        }
        void Multi<T, U, V, W>(out T a, out U b, out V c, out W d)
        {
            var ar = GetStrArray(); a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]);
        }
        void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e)
        {
            var ar = GetStrArray(); a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]);
        }
        void Multi<T, U, V, W, X, Y>(out T a, out U b, out V c, out W d, out X e, out Y f)
        {
            var ar = GetStrArray(); a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]); f = cv<Y>(ar[5]);
        }
    }

    class Edge
    {
        public Edge(int to, long length)
        {
            To = to;
            Length = length;
        }
        public int To { get; set; }
        public long Length { get; set; }
    }

    class Comparable : IComparable<Comparable>
    {
        public Comparable(int value)
        {
            Value = value;
        }

        public int Value { get; set; }
        public int CompareTo(Comparable c)
        {
            var a = Math.Abs(Value);
            var b = Math.Abs(c.Value);
            return a > b ? 1 : a == b ? 0 : -1;
        }
    }

    class Comparer<T> : IComparer<T>
    {
        public int Compare(T t1, T t2)
        {
            return 1;
        }
    }



    partial class Program
    {
        static void Main()
        {
            Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
            new AtCoder().Solve();
            Console.Out.Flush();
            Console.Read();
        }
    }

    public partial class AtCoder
    {
        public void Solve()
        {
            int H; int W;
            Multi(out H, out W);
            var map = new string[H].Select(s => GetStr().ToCharArray()).ToArray();

            var uf = new UnionFind(H * W);

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

            for(int y = 0; y < H; y++)
            {
                for(int x = 0; x < W; x++)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        var ny = y + dy[i];
                        var nx = x + dx[i];
                        if (ny < 0 || H <= ny || nx < 0 || W <= nx) continue;
                        if (map[y][x] != map[ny][nx]) uf.Union(y * W + x, ny * W + nx);
                    }   
                }
            }

            var dic = new Dictionary<int, int[]>();
            for(int y = 0; y < H; y++)
            {
                for(int x = 0; x < W; x++)
                {
                    var pos = y * W + x;
                    var parent = uf.Find(pos);
                    if (dic.ContainsKey(parent) == false) dic.Add(parent, new int[2]);
                    if (map[y][x] == '#') dic[parent][0]++;
                    else dic[parent][1]++;
                }
            }
            long ans = 0;
            foreach (var d in dic) ans += d.Value[0] * d.Value[1];
            Console.WriteLine(ans);


        }

        class UnionFind
        {
            // 親要素のインデックスを保持する
            // 親要素が存在しない(自身がルートである)とき、マイナスでグループの要素数を持つ
            int[] parents;
            public UnionFind(int n)
            {
                this.parents = new int[n];
                for (int i = 0; i < n; i++)
                {
                    // 初期状態ではそれぞれが別のグループ(ルートは自分自身)
                    // ルートなのでマイナスで要素数(1個)を保持する
                    this.parents[i] = -1;
                }
            }

            // 要素xのルート要素はどれか
            public int Find(int x)
            {
                // 親がマイナスの場合は自分自身がルート
                if (this.parents[x] < 0) return x;
                // ルートが見つかるまで再帰的に探す
                // 見つかったルートにつなぎかえる
                this.parents[x] = Find(this.parents[x]);
                return this.parents[x];
            }

            /// <summary>
            /// 要素xの属するグループの要素数を取得する
            /// </summary>
            /// <param name="x"></param>
            public int Size(int x)
            {
                // ルート要素を取得して、サイズを取得して返す
                return -this.parents[this.Find(x)];
            }

            // 要素x, yが同じグループかどうか判定する
            public bool Same(int x, int y)
            {
                return this.Find(x) == this.Find(y);
            }

            // 要素x, yが属するグループを同じグループにまとめる
            public bool Union(int x, int y)
            {
                // x, y のルート
                x = this.Find(x);
                y = this.Find(y);
                // すでに同じグループの場合処理しない
                if (x == y) return false;

                // 要素数が少ないグループを多いほうに書き換えたい
                if (this.Size(x) < this.Size(y))
                {
                    var tmp = x;
                    x = y;
                    y = tmp;
                }
                // まとめる先のグループの要素数を更新
                this.parents[x] += this.parents[y];
                // まとめられるグループのルートの親を書き換え
                this.parents[y] = x;
                return true;
            }
        }
    }
}