Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $n \cdot m$ colored pieces that form a rectangle with $n$ rows and $m$ columns. 

The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.

Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different. [Image] [Image] [Image]

These subrectangles are flags.  [Image] [Image] [Image] [Image] [Image] [Image]

These subrectangles are not flags. 


-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 1\,000$) — the number of rows and the number of columns on the blanket.

Each of the next $n$ lines contains $m$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.


-----Output-----

In the only line print the number of subrectangles which form valid flags.


-----Examples-----
Input
4 3
aaa
bbb
ccb
ddd

Output
6

Input
6 1
a
a
b
b
c
c

Output
1



-----Note----- [Image] [Image]

The selected subrectangles are flags in the first example.

Source: codeforces | Difficulty: HARD
Tags: Dynamic programming

Combinatorics

Implementation

Complete search


Solutions:
(n, m) = [int(x) for x in input().split()]
a = [[] * (m + 1) for i in range(n + 1)]
cols = [[0] * (m + 1) for i in range(n + 1)]
rows = [[0] * (m + 1) for i in range(n + 1)]
a[0] = '*' * (m + 1)
for i in range(1, n + 1):
	a[i] = '*' + input()
for i in range(1, n + 1):
	for j in range(1, m + 1):
		if a[i][j] == a[i][j - 1]:
			rows[i][j] = rows[i][j - 1] + 1
for i in range(1, n + 1):
	for j in range(1, m + 1):
		if a[i][j] == a[i - 1][j]:
			cols[i][j] = cols[i - 1][j] + 1
ans = 0
for i in range(1, n + 1):
	for j in range(1, m + 1):
		x = cols[i][j] + 1
		if i < x * 3:
			continue
		y = cols[i - x][j] + 1
		if x != y:
			continue
		z = cols[i - x - y][j] + 1
		if z < y:
			continue
		minx = 2 * m
		for l in range(0, x * 3):
			minx = min(minx, rows[i - l][j])
		ans += minx + 1
print(ans)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
(n, m) = mp()
ml = [inp() for i in range(n)]
mat = l2d(n, m)
for j in range(m):
	prevs = []
	c = 1
	for i in range(1, n):
		if ml[i][j] != ml[i - 1][j]:
			if len(prevs) > 1 and prevs[-1] <= prevs[-2] and (c == prevs[-1]):
				mat[i - 1][j] = (ml[i - 3 * c][j] + ml[i - 2 * c][j] + ml[i - c][j], c)
			prevs.append(c)
			c = 1
		else:
			if len(prevs) > 1 and prevs[-1] <= prevs[-2] and (c == prevs[-1]):
				mat[i - 1][j] = (ml[i - 3 * c][j] + ml[i - 2 * c][j] + ml[i - c][j], c)
			c += 1
	if len(prevs) > 1 and prevs[-1] <= prevs[-2] and (c == prevs[-1]):
		mat[n - 1][j] = (ml[n - 3 * c][j] + ml[n - 2 * c][j] + ml[n - c][j], c)
ans = 0
for i in range(n):
	c = 1
	for j in range(1, m):
		if mat[i][j] != mat[i][j - 1]:
			if mat[i][j - 1] != 0:
				ans += c * (c + 1) // 2
				c = 1
		elif mat[i][j] != 0:
			c += 1
	if mat[i][m - 1] != 0:
		ans += c * (c + 1) // 2
print(ans)


(n, m) = map(int, input().split())
A = [input() for _ in range(n)]
Dx = [[0] for _ in range(n)]
Dy = [[0] for _ in range(m)]
for i in range(n):
	last = None
	k = 0
	for j in range(m):
		c = A[i][j]
		if c != last:
			k = 0
		k += 1
		last = c
		Dx[i].append(k)
for j in range(m):
	last = None
	k = 0
	for i in range(n):
		c = A[i][j]
		if c != last:
			k = 0
		k += 1
		last = c
		Dy[j].append(k)
count = 0
for j in reversed(range(m)):
	col = Dy[j]
	i = len(col) - 1
	strips = []
	while i != 0:
		strips.append((col[i], i - col[i]))
		i -= col[i]
	for k in range(1, len(strips) - 1):
		if strips[k - 1][0] >= strips[k][0] <= strips[k + 1][0]:
			l = strips[k][1] - strips[k][0]
			r = strips[k - 1][1] + strips[k][0]
			res = min((Dx[i][j + 1] for i in range(l, r)))
			count += res
print(count)


import sys

def __starting_point():
	(n, m) = list(map(int, input().split()))
	arr = sys.stdin.readlines()
	f = 0
	flgs = {}
	for c in range(m):
		cnts = [[arr[0][c], 1]]
		for r in range(1, n):
			if arr[r][c] == cnts[-1][0]:
				cnts[-1][1] += 1
			else:
				cnts.append([arr[r][c], 1])
		strt = 0
		for i in range(len(cnts) - 2):
			if cnts[i][1] >= cnts[i + 1][1] <= cnts[i + 2][1]:
				lng = cnts[i + 1][1]
				beg = strt + cnts[i][1] - cnts[i + 1][1]
				clr = (cnts[i][0], cnts[i + 1][0], cnts[i + 2][0], lng)
				k = (clr, beg)
				if k in flgs and flgs[k][-1][-1] == c - 1:
					flgs[k][-1][-1] = c
				elif k in flgs:
					flgs[k].append([c, c])
				else:
					flgs[k] = [[c, c]]
			strt += cnts[i][1]
	for flg in list(flgs.values()):
		for fl in flg:
			lng = fl[1] - fl[0] + 1
			f += lng * (lng + 1) // 2
	print(f)
__starting_point()


(n, m) = map(int, input().split())
board = [input() for _ in range(n)]
u = [[1 for _ in range(m)] for _ in range(n)]
l = [[1 for _ in range(m)] for _ in range(n)]
for i in range(1, n):
	for j in range(m):
		if board[i][j] == board[i - 1][j]:
			u[i][j] = u[i - 1][j] + 1
for j in range(1, m):
	for i in range(n):
		if board[i][j] == board[i][j - 1]:
			l[i][j] = l[i][j - 1] + 1
answer = 0
for i1 in range(n):
	for j in range(m):
		k = u[i1][j]
		i2 = i1 - k
		if i2 >= 0 and u[i2][j] == k:
			i3 = i2 - k
			if i3 >= 0 and u[i3][j] >= k:
				answer += min((l[i][j] for i in range(i3 - k + 1, i1 + 1)))
print(answer)


from collections import defaultdict as dd
import math
import sys

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))
(n, m) = mi()
quilt = []
for i in range(n):
	quilt.append(li())

def getflags(column):
	flags = set()
	breaks = [0]
	for i in range(0, len(column) - 1):
		if not column[i] == column[i + 1]:
			breaks.append(i + 1)
	breaks.append(len(column))
	for j in range(1, len(breaks) - 2):
		midlength = breaks[j + 1] - breaks[j]
		firstlength = breaks[j] - breaks[j - 1]
		endlength = breaks[j + 2] - breaks[j + 1]
		if midlength <= firstlength and midlength <= endlength:
			flags.add(((breaks[j + 1], breaks[j]), (column[breaks[j + 1]], column[breaks[j]], column[breaks[j - 1]])))
	return flags
flagdicts = [0] * m
for i in range(m):
	col = [row[i] for row in quilt]
	flagdicts[i] = getflags(col)
total = 0
for i in range(m):
	for flag in flagdicts[i]:
		k = 1
		while i + k < m and flag in flagdicts[i + k]:
			k += 1
		for j in range(1, k):
			flagdicts[i + j].remove(flag)
		total += k * (k + 1) // 2
print(total)


(n, m) = map(int, input().split())
grid = []
d = {}
flags = 0
for i in range(n):
	grid.append(input())
for j in range(m):
	b = 0
	while b < n - 1:
		i = b
		k = i
		while k < n and grid[k][j] == grid[i][j]:
			k += 1
		c1 = k - i
		clr1 = grid[k - 1][j]
		i = k
		if 2 * c1 <= n - k:
			while k < n and grid[k][j] == grid[i][j]:
				k += 1
			c2 = k - i
			clr2 = grid[k - 1][j]
			i = k
			if c1 == c2 and c2 <= n - k:
				while k < n and grid[k][j] == grid[i][j]:
					k += 1
					if k - i == c2:
						break
				c3 = k - i
				clr3 = grid[k - 1][j]
				if c3 == c2:
					flags += 1
					if (c3, clr1, clr2, clr3, k - 2 * c3 - 1, k - 1) in d and d[c3, clr1, clr2, clr3, k - 2 * c3 - 1, k - 1][1] == j - 1:
						flags += d[c3, clr1, clr2, clr3, k - 2 * c3 - 1, k - 1][0]
						d[c3, clr1, clr2, clr3, k - 2 * c3 - 1, k - 1][1] = j
						d[c3, clr1, clr2, clr3, k - 2 * c3 - 1, k - 1][0] += 1
					else:
						d[c3, clr1, clr2, clr3, k - 2 * c3 - 1, k - 1] = [1, j]
		b += 1
print(flags)


from sys import stdin, stdout
(n, m) = list(map(int, stdin.readline().split()))
t = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
	s = stdin.readline().strip()
	for (j, c) in enumerate(s):
		t[i][j] = c
begins = [[False for i in range(m)] for j in range(n)]
lens = [[0 for i in range(m)] for j in range(n)]
for j in range(m):
	cur_len = 1
	run_start = 0
	for i in range(1, n):
		if t[i - 1][j] != t[i][j]:
			begins[run_start][j] = True
			for z in range(run_start, i):
				lens[z][j] = cur_len - (z - run_start)
			cur_len = 0
			run_start = i
		cur_len += 1
	begins[run_start][j] = True
	for z in range(run_start, n):
		lens[z][j] = cur_len - (z - run_start)
done = [[False for i in range(m)] for j in range(n)]
ans = 0
for j in range(m):
	for i in range(n):
		if done[i][j]:
			continue
		l = lens[i][j]
		if i + 2 * l >= n:
			continue
		if not begins[i + l][j] or lens[i + l][j] != l or (not begins[i + 2 * l][j]) or (lens[i + 2 * l][j] < l):
			continue
		num_cols = 1
		cur_j = j
		while cur_j < m and lens[i][cur_j] == l and begins[i + l][cur_j] and (lens[i + l][cur_j] == l) and begins[i + 2 * l][cur_j] and (lens[i + 2 * l][cur_j] >= l) and (t[i][cur_j] == t[i][j]) and (t[i + l][cur_j] == t[i + l][j]) and (t[i + 2 * l][cur_j] == t[i + 2 * l][j]):
			done[i][cur_j] = True
			cur_j += 1
		num_cols = cur_j - j
		ans += num_cols * (num_cols + 1) // 2
print(ans)


import sys
input = lambda : sys.stdin.readline().strip()

def f(A, r, c, l):
	(q, w, e) = (A[r][c][0], A[r][c - l][0], A[r][c - 2 * l][0])
	(x, y, z) = (A[r][c][1], A[r][c - l][1], A[r][c - 2 * l][1])
	if x != y and y != z and (e >= l) and (w == q == l):
		return (l, z, y, x)
	else:
		return 0
(r, c) = map(int, input().split())
s = ''
for i in range(r):
	s += input()
arr = []
narr = [[0] * r for i in range(c)]
for i in range(c):
	arr.append(s[i:r * c:c])
(r, c) = (c, r)
length_str = [[0] * c for i in range(r)]
for i in range(r):
	for j in range(c):
		if j == 0:
			length_str[i][j] = (1, arr[i][j])
		elif arr[i][j - 1] == arr[i][j]:
			length_str[i][j] = (length_str[i][j - 1][0] + 1, arr[i][j])
		else:
			length_str[i][j] = (1, arr[i][j])
for i in range(r):
	for j in range(c):
		(l, _) = length_str[i][j]
		if j - l * 3 + 1 < 0:
			continue
		else:
			narr[i][j] = f(length_str, i, j, l)
dp = [[0] * c for i in range(r)]
for j in range(c):
	cnt = 1
	for i in range(r):
		if narr[i][j] == 0:
			cnt = 1
			continue
		elif i == 0:
			dp[i][j] = 1
		elif narr[i][j] == narr[i - 1][j]:
			cnt += 1
			dp[i][j] = cnt
			dp[i - 1][j] = 0
		else:
			cnt = 1
			dp[i][j] = 1
ans = 0
for i in dp:
	for j in i:
		ans += j * (j + 1) // 2
print(ans)


def main():
	buf = input()
	buflist = buf.split()
	n = int(buflist[0])
	m = int(buflist[1])
	blanket = []
	for i in range(n):
		buf = input()
		blanket.append(buf)
	dp = [[]]
	for j in range(m + 1):
		dp[0].append([0, (0, '0'), (0, '0'), (0, '0'), 0])
	for i in range(n):
		dp.append([[0, (0, '0'), (0, '0'), (0, '0'), 0]])
	for i in range(n):
		for j in range(m):
			dp[i + 1].append([0, (0, None), (0, None), (0, None), 0])
			dp[i + 1][j + 1][0] = dp[i + 1][j][0] + dp[i][j + 1][0] - dp[i][j][0]
			if blanket[i][j] == dp[i][j + 1][1][1]:
				dp[i + 1][j + 1][1] = (dp[i][j + 1][1][0] + 1, dp[i][j + 1][1][1])
				dp[i + 1][j + 1][2] = dp[i][j + 1][2]
				dp[i + 1][j + 1][3] = dp[i][j + 1][3]
			else:
				dp[i + 1][j + 1][1] = (1, blanket[i][j])
				dp[i + 1][j + 1][2] = dp[i][j + 1][1]
				dp[i + 1][j + 1][3] = dp[i][j + 1][2]
			if dp[i + 1][j + 1][1][0] == dp[i + 1][j + 1][2][0] and dp[i + 1][j + 1][2][0] <= dp[i + 1][j + 1][3][0]:
				if dp[i + 1][j + 1][1] == dp[i + 1][j][1] and dp[i + 1][j + 1][2] == dp[i + 1][j][2] and (dp[i + 1][j + 1][3][1] == dp[i + 1][j][3][1]):
					dp[i + 1][j + 1][4] = dp[i + 1][j][4]
				dp[i + 1][j + 1][0] += dp[i + 1][j + 1][4] + 1
				dp[i + 1][j + 1][4] += 1
	print(dp[n][m][0])
main()


(n, m) = map(int, input().split())
a = []
flagTable = [[0] * m] * n
totalFlagNum = 0

def countFlagNum(x):
	y = 0
	flagNum = 0
	while y < m:
		curColor = a[x][y]
		colorCountByX = 1
		isItFlag = True
		while x + colorCountByX < n and a[x + colorCountByX][y] == curColor:
			colorCountByX += 1
		if not x + colorCountByX * 3 > n:
			color2 = a[x + colorCountByX][y]
			color3 = a[x + colorCountByX * 2][y]
			if color3 != color2 and color2 != curColor:
				offY = 0
				while y + offY < m and isItFlag:
					i = 0
					while i < colorCountByX and isItFlag:
						if a[x + i][y + offY] != curColor or a[x + colorCountByX + i][y + offY] != color2 or a[x + colorCountByX * 2 + i][y + offY] != color3:
							isItFlag = False
							if offY == 0:
								offY = 1
						i += 1
					if isItFlag:
						flagNum = flagNum + 1 + offY
						offY += 1
				y += offY - 1
		y += 1
	return flagNum

def markFlag():
	return 0
for i in range(n):
	row = input()
	a.append(row)
for i in range(n - 2):
	totalFlagNum += countFlagNum(i)
print(totalFlagNum)


import sys
import math
from collections import defaultdict, deque
import heapq
(n, m) = list(map(int, sys.stdin.readline().split()))
grid = []
for i in range(n):
	s = sys.stdin.readline()[:-1]
	grid.append(s)
right = [[0 for _ in range(m)] for x in range(n)]
for i in range(n):
	(l, r, cnt) = (0, 0, 0)
	while r < m:
		cnt = 0
		while r < m and grid[i][l] == grid[i][r]:
			cnt += 1
			r += 1
		while l < r:
			right[i][l] = cnt
			cnt -= 1
			l += 1
down = [[0 for _ in range(m)] for x in range(n)]
for i in range(m):
	(l, r, cnt) = (0, 0, 0)
	while r < n:
		cnt = 0
		while r < n and grid[l][i] == grid[r][i]:
			cnt += 1
			r += 1
		while l < r:
			down[l][i] = cnt
			cnt -= 1
			l += 1
ans = 0
for i in range(n):
	for j in range(m):
		x = down[i][j]
		y = 0
		if i + x < n:
			y = down[i + x][j]
		z = 0
		if i + x + y < n:
			z = down[i + x + y][j]
		if x == y and z >= y:
			minn = right[i][j]
			for k in range(i, i + 3 * x):
				minn = min(minn, right[k][j])
			ans += minn
print(ans)


import os
import sys
from io import BytesIO, IOBase

def cons(n, x):
	xx = n.bit_length()
	dp = [[10000] * n for _ in range(xx)]
	dp[0] = x[:]
	for i in range(1, xx):
		for j in range(n - (1 << i) + 1):
			dp[i][j] = min(dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
	return dp

def ask(l, r, dp):
	xx1 = (r - l + 1).bit_length() - 1
	return min(dp[xx1][l], dp[xx1][r - (1 << xx1) + 1])

def main():
	(n, m) = map(int, input().split())
	a = [input().rstrip() for _ in range(n)]
	dp = [[0] * m for _ in range(n)]
	dp1 = [[0] * m for _ in range(n)]
	dp2 = [0] * m
	for i in range(n):
		j = 0
		while j < m:
			k = j + 1
			while k < m and a[i][k] == a[i][j]:
				k += 1
			z = k - j
			for l in range(j, k):
				dp[i][l] = z
				z -= 1
			j = k
	b = [0] * n
	for j in range(m):
		i = 0
		while i < n:
			k = i + 1
			while k < n and a[k][j] == a[i][j]:
				k += 1
			z = 1
			for l in range(k - 1, i - 1, -1):
				dp1[l][j] = z
				z += 1
			i = k
		for i in range(n):
			b[i] = dp[i][j]
		dp2[j] = cons(n, b)
	ans = 0
	for i in range(n):
		for j in range(m):
			x = dp1[i][j]
			if i + x < n:
				y = dp1[i + x][j]
			else:
				continue
			if x == y and i + 3 * x - 1 < n and (dp1[i + 2 * x][j] >= x):
				(mx, my, mz) = (ask(i, i + x - 1, dp2[j]), ask(i + x, i + 2 * x - 1, dp2[j]), ask(i + 2 * x, i + 3 * x - 1, dp2[j]))
				ans += min(mx, my, mz)
			else:
				continue
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, m) = map(int, input().split())
up = [[0 for j in range(m)] for i in range(n)]
ldw = [[0 for j in range(m)] for i in range(n)]
lup = [[0 for j in range(m)] for i in range(n)]
v = []
for i in range(n):
	v.append(input())
for i in range(n):
	for j in range(m):
		if not i or v[i][j] != v[i - 1][j]:
			up[i][j] = 1
			lup[i][j] = 1 if not j or v[i][j] != v[i][j - 1] else lup[i][j - 1] + 1
		else:
			up[i][j] = up[i - 1][j] + 1
			lup[i][j] = min(lup[i - 1][j], 1 if not j or v[i][j] != v[i][j - 1] else lup[i][j - 1] + 1)
for i in range(n - 1, -1, -1):
	for j in range(m):
		if i == n - 1 or v[i][j] != v[i + 1][j]:
			ldw[i][j] = 1 if not j or v[i][j] != v[i][j - 1] else ldw[i][j - 1] + 1
		else:
			ldw[i][j] = min(ldw[i + 1][j], 1 if not j or v[i][j] != v[i][j - 1] else ldw[i][j - 1] + 1)
ans = 0
for i in range(1, n - 1):
	for j in range(m):
		if v[i][j] == v[i + 1][j]:
			continue
		h = up[i][j]
		up_st = i - h
		if up_st < 0 or up[up_st][j] < h:
			continue
		dw_st = i + h
		if dw_st >= n or up[dw_st][j] != h:
			continue
		w = min(lup[i][j], ldw[up_st - h + 1][j], lup[dw_st][j])
		ans += w
print(ans)


def return_specific_col(matrix, col_index):
	col = []
	for i in range(len(matrix)):
		col.append(matrix[i][col_index])
	return col

def make_list_to_str(lst):
	result = ''
	for e in lst:
		result += e
	return result

def find_strikes(lst):
	first = lst[0]
	counter = 1
	strikes_list = []
	for i in range(len(lst) - 1):
		if lst[i] + 1 == lst[i + 1]:
			counter += 1
		else:
			strikes_list.append(counter)
			counter = 1
	strikes_list.append(counter)
	return strikes_list

def converter(lst):
	first = lst[0]
	counter = 0
	counter_list = []
	for i in range(len(lst)):
		if lst[i] == first:
			counter += 1
		else:
			counter_list.append(counter)
			first = lst[i]
			counter = 1
	counter_list.append(counter)
	return counter_list

def solve(lst, original_col):
	if len(lst) < 3:
		return []
	counter = 0
	sum_ = 0
	poses = []
	for i in range(len(lst) - 2):
		arr = lst[i:i + 3]
		if arr[2] >= arr[1] and arr[0] >= arr[1]:
			counter += 1
			poses.append(str(sum_ + (arr[0] - arr[1])) + str(arr[1]) + make_list_to_str(original_col[sum_ + (arr[0] - arr[1]):sum_ + (arr[0] - arr[1]) + arr[1] * 3]))
		sum_ += arr[0]
	return poses
(n, m) = [int(x) for x in input().split()]
matrix = []
for i in range(n):
	matrix.append(list(input()))
if n < 3:
	print(0)
else:
	strikes_dict = {}
	for j in range(m):
		for row_length in solve(converter(return_specific_col(matrix, j)), return_specific_col(matrix, j)):
			if row_length in strikes_dict:
				strikes_dict[row_length].append(j)
			else:
				strikes_dict[row_length] = [j]
	counter = 0
	for row_length in strikes_dict:
		row_length = find_strikes(strikes_dict[row_length])
		for i in row_length:
			counter += (1 + i) * i // 2
	print(counter)


(n, m) = list(map(int, input().split()))
a = [input() for i in range(n)]
(b, c) = ([[0 for i in range(m)] for j in range(n)], 0)
for i in range(n):
	for j in range(m):
		if i == 0 or a[i][j] != a[i - 1][j]:
			b[i][j] = 1
		else:
			b[i][j] = b[i - 1][j] + 1
w = 0
for i in range(2, n):
	for j in range(m):
		f = i - b[i][j]
		if f > 0:
			g = f - b[f][j]
			if g != -1:
				if b[i][j] == b[f][j] and b[g][j] >= b[i][j]:
					if j == 0 or b[i][j] != b[i][j - 1] or a[i][j] != a[i][j - 1] or (a[f][j] != a[f][j - 1]) or (a[g][j] != a[g][j - 1]):
						w = 0
					w += 1
				else:
					w = 0
			else:
				w = 0
		else:
			w = 0
		c += w
print(c)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(input()))
if n < 3:
	print(0)
	sys.exit(0)
a = [[1 for i in range(m)] for j in range(n)]
a1 = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
	for j in range(m):
		if i == 0 or l[i][j] != l[i - 1][j]:
			a[i][j] = 1
		else:
			a[i][j] = a[i - 1][j] + 1
ans = 0
for i in range(n):
	for j in range(m):
		t = a[i][j]
		if i < 2 * t or a[i - t][j] != t or a[i - 2 * t][j] < t:
			continue
		elif j == 0:
			a1[i][j] = 1
			ans += 1
			continue
		elif a[i][j] == a[i][j - 1] and l[i][j] == l[i][j - 1] and (l[i - t][j] == l[i - t][j - 1]) and (l[i - 2 * t][j] == l[i - 2 * t][j - 1]):
			a1[i][j] = a1[i][j - 1] + 1
			ans += a1[i][j]
		else:
			a1[i][j] = 1
			ans += 1
print(ans)


(n, m) = map(int, input().split())
grid = []
for i in range(n):
	s = input()
	grid.append(s)
grid2 = []
for i in range(n):
	grid2.append([])
	for j in range(m):
		grid2[-1].append(0)
for j in range(m):
	lastchar = ''
	int1 = 0
	int2 = 0
	int3 = 0
	for i in range(n):
		if grid[i][j] == lastchar:
			int3 += 1
		else:
			int1 = int2
			int2 = int3
			int3 = 1
			lastchar = grid[i][j]
		if int1 >= int2 and int2 == int3:
			grid2[i][j] = int3
score = []
for i in range(n):
	score.append([])
	for j in range(m):
		score[-1].append(0)
for i in range(n):
	for j in range(m):
		t = grid2[i][j]
		if t > 0:
			if j > 0 and grid2[i][j - 1] == t and (grid[i][j] == grid[i][j - 1]) and (grid[i - t][j] == grid[i - t][j - 1]) and (grid[i - 2 * t][j - 1] == grid[i - 2 * t][j]):
				score[i][j] = score[i][j - 1] + 1
			else:
				score[i][j] = 1
ans = 0
for i in range(n):
	for j in range(m):
		ans += score[i][j]
print(ans)


(a, b) = map(int, input().split())
c = [[0] * b for i in range(a)]
d = [input() for i in range(a)]
for j in range(b):
	n = []
	pred = d[0][j]
	cnt = 1
	for i in range(1, a):
		if d[i][j] == pred:
			cnt += 1
		else:
			n.append((cnt, pred))
			cnt = 1
		pred = d[i][j]
	n.append((cnt, pred))
	uk = 0
	for i in range(2, len(n)):
		if n[i - 2][0] >= n[i - 1][0] and n[i - 1][0] <= n[i][0]:
			c[uk + n[i - 2][0] - n[i - 1][0]][j] = [n[i - 2][1], n[i - 1][1], n[i][1], n[i - 1][0]]
		uk += n[i - 2][0]
summ = 0
cnt = 0
if b == 1:
	for i in range(a):
		for j in range(b):
			if c[i][j] != 0:
				summ += 1
	print(summ)
	exit(0)
for i in range(a):
	cnt = 0
	f = False
	for j in range(1, b):
		if cnt == 0 and c[i][j - 1] != 0:
			cnt = 1
		if c[i][j - 1] == c[i][j] and c[i][j] != 0:
			cnt += 1
		elif c[i][j] != 0:
			summ += cnt * (cnt + 1) // 2
			cnt = 1
		else:
			summ += cnt * (cnt + 1) // 2
			cnt = 0
	summ += cnt * (cnt + 1) // 2
print(summ)


def number_rectangle(h):
	l = [0 for i in range(len(h))]
	stack = []
	dp = [0 for i in range(len(h))]
	result = 0
	for i in range(len(h)):
		while len(stack) > 0 and stack[-1] >= h[i]:
			stack.pop()
		if len(stack) == 0:
			dp[i] = i + 1
		else:
			dp[i] = dp[stack[-1]] + (i - stack[-1]) * h[i]
		result += dp[i]
	return result

def main():
	(rows, cols) = list(map(int, input().split()))
	rows += 1
	a = []
	a.append('-' * cols)
	for i in range(1, rows):
		a.append(input())
	h = [[0 for j in range(cols)] for i in range(rows)]
	result = 0
	for i in range(1, rows):
		last_state = (0, 0, 0, 0, 0, 0)
		same_state = 0
		sub = []
		for j in range(0, cols):
			if a[i][j] == a[i - 1][j]:
				h[i][j] = h[i - 1][j] + 1
			else:
				h[i][j] = 1
			i2 = i - h[i][j]
			i3 = i2 - h[i2][j]
			curr_state = (h[i][j], h[i2][j], a[i][j], a[i2][j], a[i3][j])
			if h[i][j] == h[i2][j] and h[i3][j] >= h[i][j]:
				if curr_state == last_state:
					sub.append(h[i3][j] - h[i][j])
				else:
					result += number_rectangle(sub)
					sub.clear()
					sub.append(h[i3][j] - h[i][j])
			else:
				result += number_rectangle(sub)
				sub.clear()
			last_state = curr_state
		result += number_rectangle(sub)
	result = int(result)
	print(result)
main()


import os
from io import BytesIO, StringIO
DEBUG = True
debug_print = print if DEBUG else lambda *x, **y: None

def input_as_list():
	return list(map(int, input().split()))

def array_of(f, *dim):
	return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()

def main():
	(n, m) = input_as_list()
	g = [input() for _ in range(n)]
	prev_flgs = dict()
	s = 0
	for j in range(m):
		lst = []
		prev = ''
		cnt = 0
		for i in range(n):
			e = g[i][j]
			if e == prev:
				cnt += 1
			else:
				if prev:
					lst.append((prev, cnt))
				prev = e
				cnt = 1
		lst.append((e, cnt))
		flgs = dict()
		idx = 0
		for i in range(len(lst) - 2):
			(f1, f2, f3) = (lst[i], lst[i + 1], lst[i + 2])
			if f1[1] == f2[1] == f3[1]:
				flgs[idx] = [f1[0] + f2[0] + f3[0], f1[1], 1]
			elif min(f1[1], f2[1], f3[1]) == f2[1]:
				flgs[idx + f1[1] - f2[1]] = [f1[0] + f2[0] + f3[0], f2[1], 1]
			idx += f1[1]
		if prev_flgs:
			for f in flgs:
				if f in prev_flgs:
					fv = flgs[f]
					pfv = prev_flgs[f]
					if fv[0] == pfv[0] and fv[1] == pfv[1]:
						s += pfv[2] + 1
						flgs[f][2] = pfv[2] + 1
					else:
						s += 1
				else:
					s += 1
		else:
			s += len(flgs)
		prev_flgs = flgs
	print(s)
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, m) = RL()
	arr = [list(input()) for _ in range(n)]
	dp = [[1] * m for _ in range(n)]
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if dp[i][j] != 1:
				continue
			now = i
			while now - 1 >= 0 and arr[now - 1][j] == arr[now][j]:
				dp[now - 1][j] = dp[now][j] + 1
				now -= 1
	res = 0
	for i in range(n):
		j = 0
		while j < m:
			mid = dp[i][j]
			if i - 1 < 0 or arr[i][j] == arr[i - 1][j] or i + mid >= n or (i - mid < 0):
				j += 1
				continue
			low = dp[i + mid][j]
			up = dp[i - mid][j]
			if mid <= low and mid == up:
				ma = 1
				for k in range(j + 1, m):
					nmid = dp[i][k]
					nlow = dp[i + mid][k]
					nup = dp[i - mid][k]
					if nmid == mid and nmid <= nlow and (nmid == nup) and (arr[i][k] == arr[i][j]) and (arr[i + mid][k] == arr[i + mid][j]) and (arr[i - mid][k] == arr[i - mid][j]):
						ma = max(ma, k - j + 1)
					else:
						break
				j = j + ma - 1
				res += (1 + ma) * ma // 2
			j += 1
	print(res)
main()


(H, W) = map(int, input().split())
G = [[ord(s) - 96 for s in input().strip()] for _ in range(H)]
G = list(map(list, zip(*G)))
A = [None] * W
B = [None] * W
Col = [None] * W
Dic = [None] * W
for (j, Gi) in enumerate(G):
	pre = -1
	D = [None] * H
	con = 0
	ctr = 0
	E = [None] * H
	F = []
	for (i, g) in enumerate(Gi):
		if pre != g:
			F.append(con)
			ctr += 1
			con = 0
		con += 1
		D[i] = con
		pre = g
		E[i] = ctr
	F.append(con)
	Col[j] = E[:]
	Dic[j] = F[:]
	B[j] = D[:]
	pm = 0
	pre = -1
	for (i, (g, d)) in enumerate(zip(Gi[::-1], D[::-1])):
		if pre != g:
			pm = 0
		pm = max(pm, d)
		D[H - 1 - i] = pm
		pre = g
	A[j] = D[:]
C = [[0] * H for _ in range(W)]
for w in range(W):
	for h in range(H):
		c = Col[w][h]
		if c + 2 >= len(Dic[w]):
			continue
		leng = A[w][h] + 1 - B[w][h]
		if Dic[w][c + 1] == leng and Dic[w][c + 2] >= leng:
			C[w][h] = leng * 10 ** 6 + 900 * G[w][h] + 30 * G[w][h + leng] + G[w][h + 2 * leng]
C = list(map(list, zip(*C)))
ans = 0
for Ci in C:
	ctr = 0
	pre = -1
	for c in Ci:
		if not c:
			pre = -1
			continue
		if c != pre:
			ans += ctr * (ctr + 1) // 2
			ctr = 1
		else:
			ctr += 1
		pre = c
	ans += ctr * (ctr + 1) // 2
print(ans)


def test_c(n, m, G):
	mid = [[False for i in range(m)] for j in range(n)]
	vis = [[False for i in range(m)] for j in range(n)]
	L = [[1 for i in range(m)] for j in range(n)]
	for i in range(1, n):
		for j in range(m):
			if G[i][j] != G[i - 1][j]:
				mid[i][j] = True
	for j in range(m):
		for i in range(n):
			if i >= 1 and G[i][j] == G[i - 1][j]:
				L[i][j] = L[i - 1][j] - 1
				continue
			k = 0
			while i + k < n and G[i][j] == G[i + k][j]:
				k += 1
			L[i][j] = k
	cnt = 0
	for i in range(n):
		for j in range(m):
			if mid[i][j] == True and vis[i][j] == False:
				if i - L[i][j] >= 0 and i + L[i][j] < n:
					if L[i - L[i][j]][j] == L[i][j] and L[i + L[i][j]][j] >= L[i][j]:
						k = 1
						vis[i][j] = True
						while j + k < m and G[i][j] == G[i][j + k] and (L[i][j] == L[i][j + k]) and (mid[i][j + k] == True):
							if L[i - L[i][j]][j + k] == L[i][j] and G[i - L[i][j]][j + k] == G[i - L[i][j]][j] and (L[i + L[i][j]][j + k] >= L[i][j]) and (G[i + L[i][j]][j + k] == G[i + L[i][j]][j]):
								vis[i][j + k] = True
								k += 1
							else:
								break
						cnt += int((k + 1) * k // 2)
	print(cnt)

def __starting_point():
	(n, m) = [int(x) for x in input().split()]
	G = []
	for i in range(n):
		G.append(list(input()))
	mid = [[False for i in range(m)] for j in range(n)]
	vis = [[False for i in range(m)] for j in range(n)]
	L = [[1 for i in range(m)] for j in range(n)]
	for i in range(1, n):
		for j in range(m):
			if G[i][j] != G[i - 1][j]:
				mid[i][j] = True
	for j in range(m):
		for i in range(n):
			if i >= 1 and G[i][j] == G[i - 1][j]:
				L[i][j] = L[i - 1][j] - 1
				continue
			k = 0
			while i + k < n and G[i][j] == G[i + k][j]:
				k += 1
			L[i][j] = k
	cnt = 0
	for i in range(n):
		for j in range(m):
			if mid[i][j] == True and vis[i][j] == False:
				if i - L[i][j] >= 0 and i + L[i][j] < n:
					if L[i - L[i][j]][j] == L[i][j] and L[i + L[i][j]][j] >= L[i][j]:
						k = 1
						vis[i][j] = True
						while j + k < m and G[i][j] == G[i][j + k] and (L[i][j] == L[i][j + k]) and (mid[i][j + k] == True):
							if L[i - L[i][j]][j + k] == L[i][j] and G[i - L[i][j]][j + k] == G[i - L[i][j]][j] and (L[i + L[i][j]][j + k] >= L[i][j]) and (G[i + L[i][j]][j + k] == G[i + L[i][j]][j]):
								vis[i][j + k] = True
								k += 1
							else:
								break
						cnt += int((k + 1) * k // 2)
	print(cnt)
__starting_point()


(n, m) = [int(i) for i in input().split()]
data = []
for i in range(n):
	data.append(list(input()))
f = []
for i in range(m):
	temp = []
	prev = 0
	cnt = 0
	for j in range(n):
		ch = ord(data[j][i]) - 95
		if ch == prev:
			cnt += 1
		else:
			temp.append((prev, cnt, j - cnt))
			prev = ch
			cnt = 1
	temp.append((prev, cnt, n - cnt))
	for t in range(1, len(temp) - 1):
		td = temp[t - 1]
		tf = temp[t + 1]
		te = temp[t]
		if te[0] != td[0] and te[0] != tf[0] and (td[1] >= te[1]) and (tf[1] >= te[1]):
			f.append((te[2], i, te[1], (td[0] << 10) + (te[0] << 5) + tf[0]))
tot = 0
f.sort()
le = len(f)
i = 0
while i < le:
	d = f[i]
	cnt = 1
	while i < le - 1 and d[1] + cnt == f[i + 1][1] and (d[0] == f[i + 1][0]) and (d[2] == f[i + 1][2]) and (d[3] == f[i + 1][3]):
		i += 1
		cnt += 1
	tot += cnt * (cnt + 1) // 2
	i += 1
print(tot)


import os, sys
from io import BytesIO, IOBase

def cons(n, x):
	xx = n.bit_length()
	dp = [[10 ** 9] * n for _ in range(xx)]
	dp[0] = x
	for i in range(1, xx):
		for j in range(n - (1 << i) + 1):
			dp[i][j] = min(dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
	return dp

def ask(l, r, dp):
	xx1 = (r - l + 1).bit_length() - 1
	return min(dp[xx1][l], dp[xx1][r - (1 << xx1) + 1])

def solve(n, arr, pre):
	(count, start, c) = ([], [], 1)
	for i in range(1, n):
		if arr[i] == arr[i - 1]:
			c += 1
		else:
			count.append(c)
			start.append(i - c)
			c = 1
	count.append(c)
	start.append(n - c)
	ans = 0
	for i in range(1, len(count) - 1):
		if count[i - 1] >= count[i] <= count[i + 1]:
			(l, r) = (start[i] - count[i], start[i] + 2 * count[i] - 1)
			ans += ask(l, r, pre)
	return ans

def main():
	(n, m) = map(int, input().split())
	arr = [input() for _ in range(n)]
	dp = [[1] * m for _ in range(n)]
	for i in range(n):
		for j in range(m - 2, -1, -1):
			if arr[i][j] == arr[i][j + 1]:
				dp[i][j] += dp[i][j + 1]
	print(sum((solve(n, [arr[i][j] for i in range(n)], cons(n, [dp[i][j] for i in range(n)])) for j in range(m))))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()