Problem:


Score : 400 points

Problem Statement

We have an H-by-W matrix.
Let a_{ij} be the element at the i-th row from the top and j-th column from the left.
In this matrix, each a_{ij} is a lowercase English letter.

Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A.
Here, he wants to satisfy the following condition:

Every row and column in A' can be read as a palindrome.

Determine whether he can create a matrix satisfying the condition.

Note

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and abcba are all palindromes, while ab, abab and abcda are not.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}

Output

If Snuke can create a matrix satisfying the condition, print Yes; otherwise, print No.

Sample Input 1

3 4
aabb
aabb
aacc

Sample Output 1

Yes

For example, the following matrix satisfies the condition.

abba
acca
abba

Sample Input 2

2 2
aa
bb

Sample Output 2

No

It is not possible to create a matrix satisfying the condition, no matter how we rearrange the elements in A.

Sample Input 3

5 1
t
w
e
e
t

Sample Output 3

Yes

For example, the following matrix satisfies the condition.

t
e
w
e
t

Sample Input 4

2 5
abxba
abyba

Sample Output 4

No

Sample Input 5

1 1
z

Sample Output 5

Yes



Sample input:
3 4
aabb
aabb
aacc


Sample output:
Yes

Submission status: Accepted

Solution code:
from collections import Counter
from math import floor

def solve():
    h, w = map(int, input().split())
    word_dict = dict(Counter(list("".join([input() for _ in range(h)]))))

    g1 = (w % 2) & (h % 2)
    g2 = floor((w % 2) * h/2) + floor((h % 2) * w/2)
    g4 = floor(h/2) * floor(w/2)
    
    for k, v in word_dict.items():
        if (g1 > 0) and v % 4 == 1 or v % 4 == 3:
            g1 -= 1
            word_dict[k] -= 1
            v -= 1
        while (g4 > 0) and v >= 4:
            g4 -= 1
            word_dict[k] -= 4
            v -= 4
        while (g2 > 0) and v >= 2:
            g2 -= 1
            word_dict[k] -= 2
            v -= 2
            
    print("No" if [1 for v in word_dict.values() if v != 0] else "Yes")
    
if __name__=="__main__":
    solve()

Submission status: Accepted

Solution code:
from collections import Counter
from math import floor

def solve():
    h, w = map(int, input().split())
    word_dict = dict(Counter(list("".join([input() for _ in range(h)]))))

    g1 = (w % 2) & (h % 2)
    g2 = floor((w % 2) * h/2) + floor((h % 2) * w/2)
    g4 = floor(h/2) * floor(w/2)
    
    for k, v in word_dict.items():
        if g1 == 0:
            break
        if v % 4 == 1 or v % 4 == 3:
            g1 -= 1
            word_dict[k] -= 1
            v -= 1
            
    for k, v in word_dict.items():
        if g4 == 0:
            break
        while v >= 4:
            g4 -= 1
            word_dict[k] -= 4
            v -= 4

    for k, v in word_dict.items():
        if g2 == 0:
            break
        while v >= 2:
            g2 -= 1
            word_dict[k] -= 2
            v -= 2
            
    print("No" if [1 for v in word_dict.values() if v != 0] else "Yes")
    
if __name__=="__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
lines = sys.stdin.readlines()
R, C = tuple(int(i) for i in lines[0].split(' '))
lines = ''.join(i.strip() for i in lines[1:])


def doD(cs):
    d = {}
    for c in cs:
        if c not in d: d[c] = 0
        d[c] += 1
    return d

def doAns(b):
    print('Yes' if b else 'No')
    sys.exit(0)

def meme(d, rem, val):
    remc = []
    d2 = {}
    for k,v in d.items():
        count = v % val
        remc += [k]*count
        rem -= count
        d2[k] = v - count
    if rem > 0:
        for k,v in d2.items():
           while v >= val and rem > 0:
               v -= val
               rem -= val
               remc += [k]*val
    return (rem, ''.join(remc))

if R == 1 and C == 1:
    doAns(True)
elif R == 1 or C == 1:
    rem = (R + C + 1)%2
    doAns(meme(doD(lines), rem, 2)[0] == 0)
elif R % 2 == 0 and C % 2 == 0:
    doAns(meme(doD(lines), 0, 4)[0] == 0)

rem = (R%2) * C + (C%2)*R
if R % 2 + C % 2 == 1:
    rem, remc = meme(doD(lines), rem, 4)
    if rem != 0: doAns(False)
    rem, remc = meme(doD(remc), len(remc)%2, 2)
    doAns(rem == 0)
    
if R%2 and C%2:
    rem -= 1
    rem, remc = meme(doD(lines), rem, 4)
    if rem != 0: doAns(False)
    rem, remc = meme(doD(remc), C-(R+1)%2, 2)    
    if rem != 0: doAns(False)
    rem, remc = meme(doD(remc), C%2, 2)
    doAns(rem == 0)

Submission status: Accepted

Solution code:
def i1():
 return int(input())
def i2():
 return [int(i) for i in input().split()]

[h,w]=i2()
a=""
for i in range(h):
    a+=input()
from collections import Counter
c=Counter(list(a))
c=list(c.values())
b2=0
b4=0
b1=0
if h%2==1 and w%2==0:
 b2=w//2
if w%2==1 and h%2==0:
 b2=h//2
if w%2==1 and h%2==1:
 b1=1
 b2=w//2+h//2
s="Yes"
b4=(h*w-b2*2)//4
for i in c:
    if i%4==0:
     if b4-i//4>=0:
        b4-=i//4
     elif b2-(i-4*b4)//2>=0:
        b2-=(i-4*b4)//2
        b4=0
     else:
        s="No"
    elif i%2==0:
      if i>=4:
          if b4-i//4>=0:
             b4-=i//4
             if b2-i%4//2>=0:
                 b2-=i%4//2
             else:
                 s="No"
          elif b2-i//2>=0:
             b2-=i//2
          else:
             s="No"
      elif i==2 and b2>=1:
          b2-=1
      else:
          s="No"
    else:
        if b1==1:
          b1=0
          t=i-1
          if t>0:
            if t%4==0:
             if b4-t//4>=0:
                b4-=t//4
             elif b2-(t-b4*4)//2>=0:
                t-=4*b4
                b4=0
                b2-=t//2
             else:
                s="No"
            elif t%2==0:
              if t>=4:
                  if b4-t//4>=0:
                     b4-=t//4
                     if b2-t%4//2>=0:
                         b2-=t%4//2
                     else:
                         s="No"
                  elif b2-(t-b4*4)//2>=0:
                     t-=4*b4
                     b4=0
                     b2-=t//2
                  else:
                     s="No"
              elif t==2 and b2>=1:
                  b2-=1
              else:
                  s="No"

        else:
           s="No"
print(s)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
cnt=[0]*26
for i in range(n):
	for j in input():
		cnt[ord(j)-ord('a')]+=1
if n%2==1: n,m=m,n
c4,c1=(n//2)*(m//2),m%2
if n%2:
	c2=(n//2)+(m//2)
elif m%2:
	c2=n//2
else:
	c2=0
for i in range(26):
	while c4>0 and cnt[i]>=4:
		cnt[i]-=4
		c4-=1
	while c2>0 and cnt[i]>=2:
		cnt[i]-=2
		c2-=1
	while c1>0 and cnt[i]>=1:
		cnt[i]-=1
		c1-=1
	if cnt[i]>0:
		print("No")
		quit()
print("Yes")

Submission status: Accepted

Solution code:
H,W = map(int,input().strip().split())
lines = []
for i in range(H):
    lines.append(input().strip())
chars = {}
for line in lines:
    for c in line:
        if c not in chars:
            chars[c]=0
        chars[c]+=1

def judge(H,W,chars):
    if H%2 + W%2==2:
        ones = 1
        twos = (H + W - 2)//2
    elif H%2 + W%2==0:
        ones = 0
        twos = 0
    elif H%2 == 1:
        ones = 0
        twos = W//2
    else:
        ones = 0
        twos = H//2
    for c in chars:
        if ones<0 or twos<0:
            return False
        chars[c] %= 4
        if chars[c]==0:
            continue
        if chars[c] == 2:
            twos-=1
        elif chars[c] == 3:
            twos-=1
            ones-=1
        else:
            ones-=1
    return True


if judge(H, W, chars):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import sys
import socket
from collections import Counter

hostname = socket.gethostname()

if hostname == 'F451C':
    sys.stdin = open('c1.in')


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


def read_str_list():
    return input().split()


def read_int():
    return int(input())


def read_str():
    return input()


def main():
    h, w = read_int_list()
    c = Counter()
    for i in range(h):
        a = read_str()
        c += Counter(a)

    n4 = (h - h % 2) * (w - w % 2) // 4
    n2 = 0
    if h % 2 == 1:
        n2 += w // 2
    if w % 2 == 1:
        n2 += h // 2
    n1 = 0
    if h % 2 == 1 and w % 2 == 1:
        n1 = 1

    v = [4] * n4 + [2] * n2 + [1] * n1
    l = list(c.values())
    for x in v:
        l.sort(reverse=True)
        if l[0] < x:
            print('No')
            return
        else:
            l[0] -= x
    print('Yes')


main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import array
from bisect import *
from collections import *
import fractions
import heapq 
from itertools import *
import math
import re
import string

def valid(two_num, four_num, one_num, c):
    t = 0
    f = 0
    o = 0
    for v in c.values():
        while v >= 4:
            f += 1
            v -= 4
        if v >= 2:
            t += 1
            v -= 2
        if v == 1:
            o += 1
            v -= 1
    if one_num == 1:
        return o == 1 and f * 4 >= four_num
    else:
        return o == 0 and f * 4 >= four_num
        

H, W = map(int, input().split())
c = Counter()
for h in range(H):
    s = input()
    c.update(s)

def solve(H, W, c):
    ok = True
    if H == W == 1:
        pass
    elif H == 1 or W == 1:
        HW = H * W
        odd_num = sum(1 for x in c.values() if x % 2)
        even_num = HW - odd_num
        # print("odd, even = ", odd_num, even_num)
        if HW % 2 == 1 and odd_num != 1: ok = False
        elif HW % 2 == 0 and odd_num != 0: ok = False
    elif H % 2 == W % 2 == 0:
        # all 4
        for v in c.values():
            if v % 4 != 0:
                ok = False
                break
    elif H % 2 == W % 2 == 1:
        two_num = H + W - 2
        one_num = 1
        four_num = H * W - two_num - one_num
        if not valid(two_num, four_num, one_num, c):
            ok = False
    else:
        if W % 2 == 0:
            two_num = W
        else:
            two_num = H
        four_num = H * W - two_num
        if not valid(two_num, four_num, 0, c):
            ok = False
        
    return ok

if solve(H, W, c):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
H, W = list(map(int, input().split()))
dic = {}

for i in range(H):
    S = input()
    for j in range(W):
        dic[S[j]] = dic.get(S[j], 0) + 1

N = ((W + 1)//2) * ((H + 1) // 2)
needFour = (W // 2) * (H // 2)
needOne = (W % 2) * (H % 2)
needTwo = N - needFour - needOne

pare = [0, 0, 0]
for v in dic.values():
    pare[0] += v//4
    pare[1] += (v%4)//2
    pare[2] += v % 2

if pare[0] < needFour:
    print("No")
else:
    pare[1] += (pare[0] - needFour) * 2
    if pare[1] < needTwo:
        print("No")
    else:
        pare[2] += (pare[1] - needTwo) * 2
        if pare[2] < needOne:
            print("No")
        else:
            print("Yes")

Submission status: Accepted

Solution code:
h, w = list(map(int, input().split()))
a = [0]*26
for i in range(h):
    s = input()
    for j in range(w):
        a[ord(s[j]) - ord("a")] += 1

soto = 0
for i in range(26):
    soto += int(4*(a[i] // 4))
    a[i] -= int(4*(a[i] // 4))

amari = 0

if (h + w) % 2 == 1:
    if h % 2 == 0:
        b = h
    else:
        b = w
    if soto < h * w - b:
        print("No")
    else:
        for i in range(len(a)):
            if a[i] % 2 == 1:
                print("No")
                break
            if i == 25:
                print("Yes")

elif h % 2 == 0 and w % 2 == 0:
    if soto == h * w:
        print("Yes")
    else:
        print("No")

else:
    if soto < h * w  - h - w  + 1:
        print("No")
    else:
        flag = 0
        for i in range(26):
            if a[i] % 2 == 1 and flag == 0:
                flag = 1
            elif a[i] % 2 == 1 and flag == 1:
                print("No")
                break
            if i == 25:
                print("Yes")

Submission status: Accepted

Solution code:
from collections import Counter

H, W = map(int, input().split())
a = ""

for _ in range(H):
    a = a + input()

c = Counter(a)

s_4 = 0
s_2 = 0
s_1 = 0

for _, x in c.most_common():
    s_4 += x//4
    s_2 += (x%4)//2
    s_1 += x%2
    
a_4 = (H//2)*(W//2)
a_2 = (H//2)*(W%2)+(W//2)*(H%2)
a_1 = (H%2)*(W%2)

if s_4 - a_4 < 0:
    print("No")
elif (s_2+(s_4 - a_4)*2) - a_2 < 0:
    print("No")
else:
    print("Yes")

Submission status: Accepted

Solution code:
import numpy as np
import string

alphabets = "abcdefghijklmnopqrstuvwxyz"

h, w = map(int, input().split(" "))

txt = np.zeros(26, dtype = int)

for i in range(h):
    a = input()
    for j in a:
        txt[alphabets.index(j)] += 1

one = 0
if(h % 2 != 0 and w % 2 != 0):
    one += 1

all = h * w - one

flag = 1
if(one == 1):
    flag = 0
    for i in range(26):
        if(txt[i] % 2 != 0):
            txt[i] -= 1
            flag = 1
            break
num = int(h / 2) * int(w / 2)

while(flag == 1 and all > 0 and num > 0):
    flag = 0
    for i in range(26):
        if(txt[i] > 3):
            txt[i] -= 4
            all -= 4
            flag = 1
            break
    num -= 1

for i in range(26):
     if(txt[i] % 2 != 0):
         flag = 0
         break



if(flag == 1):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import itertools
import sys

h, w = map(int, input().split())

a = [input() for i in range(h)]
words = list(set(itertools.chain(*a)))
at = list(itertools.chain(*a))

mods = []
for word in words:
    for i in range(at.count(word) // 4):
        mods.append(4)
    mod = at.count(word) % 4
    if mod:
        mods.append(mod)

mods = list(sorted(mods))
def count_down(l, n):
    for i in range(len(l)):
        if l[i] - n >= 0:
            l[i] -= n
            if not l[i]:
                del l[i]
            return True
    return False

if h % 2 and w % 2:
    flg = True
    for i in range(w // 2 + h // 2):
        flg = count_down(mods, 2)
    if flg and count_down(mods, 1) and mods.count(4) == len(mods):
        print("Yes")
        sys.exit()

elif h % 2:
    flg = False
    for i in range(w // 2):
        flg = count_down(mods, 2)
    if flg and mods.count(4) == len(mods):
        print("Yes")
        sys.exit()

elif w % 2:
    flg = False
    for i in range(h // 2):
        flg = count_down(mods, 2)
    if flg and mods.count(4) == len(mods):
        print("Yes")
        sys.exit()

else:
    if mods.count(4) == len(mods):
        print("Yes")
        sys.exit()

print("No")

Submission status: Accepted

Solution code:
from collections import defaultdict

def foo():
	H, W = map(int, input().split())
	s = ""
	for _ in range(H):
		s += input()

	counter = defaultdict(int)
	for c in s:
		counter[c] += 1

	x1, x2 = H // 2, H % 2
	y1, y2 = W // 2, W % 2

	n = x1 * y1
	k = 0
	for c in counter:
		if k == n:
			break
		while k != n and counter[c] >= 4:
			k += 1
			counter[c] -= 4

	if k != n:
		print("No")
		return

	if x2 == 1:
		n = y1
		k = 0
		for c in counter:
			if k == n:
				break
			while k != n and counter[c] >= 2:
				k += 1
				counter[c] -= 2
		if k != n:
			print("No")
			return

	if y2 == 1:
		n = x1
		k = 0
		for c in counter:
			if k == n:
				break
			while k != n and counter[c] >= 2:
				k += 1
				counter[c] -= 2
		if k != n:
			print("No")
			return
			
	print("Yes")

foo()

Submission status: Accepted

Solution code:
# coding: utf-8
# Here your code !

H , W  = input().split()
H = int(H)
W = int(W)
OK = False

st = ""
for n in range(H):
    st += input()
    
counter = {}
for c in st:
    if not c in counter:
        counter[c] = 1
    else:
        counter[c] += 1

#H,Wが偶数の時
if (H % 2 == 0) & (W % 2 == 0) :
    for i in counter.keys():
        if not (counter[i] % 4 == 0) : 
            #一度でも4の倍数でなかったらだめ
            OK = False
            break
        OK = True
elif (H % 2 != 0) & (W % 2 != 0) :
    #一個の奴が必ず一つある -> 奇数が必ず一つある
    kisuuCounter = 0
    for i in counter.keys():
        if counter[i] % 2 == 1 : 
            kisuuCounter += 1
            kisuu = i
    
    if kisuuCounter == 1 : 
        counter[kisuu] -= 1
        twoPair = (W + H - 2) / 2
        q = {i : (counter[i] % 4) / 2 for i in counter.keys()}
        p = {i: (counter[i] - 2*q[i]) / 4 for i in counter.keys() }
        
        x = twoPair - sum(q.values())
        if (x >= 0) & (x % 2 == 0) & (x <= 2 * sum(p.values())) : 
            OK = True
else :
    kisuuCounter = 0
    for i in counter.keys():
        if counter[i] % 2 == 1 : 
            kisuuCounter += 1
            kisuu = i
    
    if kisuuCounter == 0 :
        if H % 2 == 0 : 
            twoPair = H / 2
        else : 
            twoPair = W / 2
        
        q = {i : (counter[i] % 4) / 2 for i in counter.keys()}
        p = {i: (counter[i] - 2*q[i]) / 4 for i in counter.keys() }
        x = twoPair - sum(q.values())
        if (x >= 0) & (x % 2 == 0) & (x <= 2 * sum(p.values())) : 
            OK = True
        
if OK : print("Yes")
else : print("No")

Submission status: Accepted

Solution code:
from sys import stdin
n,m = map(int,stdin.readline().split())
di = {}
for _ in xrange(n):
    a = stdin.readline().strip()
    for i in a:
        di[i] = di.get(i,0) + 1
ev = 0
od = 0
for i in di:
    if di[i]%4==2:
        ev+=1
    elif di[i]%4==3:
        od+=1
        ev+=1
    elif di[i]%4==1:
        od+=1
ans = 'Yes'
if od>1:
    ans = 'No'
elif (n*m)%2==0 and od>0:
    ans = 'No'
else:
    if n%2==0 and m%2==0:
        if ev > 0:
            ans = 'No'
    elif n%2==0:
        if ev > n/2:
            ans = 'No'
    elif m%2==0:
        if ev > m/2:
            ans = 'No'
    else:
        if ev > (n/2) + (m/2):
            ans = 'No'
print ans

Submission status: Accepted

Solution code:
# encoding:utf-8
def needs(n_row, n_col):
	if n_row % 2 + n_col % 2 == 0:
		return [(n_row // 2) * (n_col // 2), 0, 0]
	elif n_row % 2 + n_col % 2 == 2:
		return [(n_row // 2) * (n_col // 2), (n_row // 2) + (n_col // 2), 1]
	elif n_row % 2 == 1:
		return [(n_row // 2) * (n_col // 2), n_col // 2, 0]
	else:
		return [(n_row // 2) * (n_col // 2), n_row // 2, 0]

def alphabetCount(input_lines):
	alphabet = "abcdefghijklmnopqrstuvwxyz"
	counter = [0, 0, 0]
	for i in range(26):
		count = input_lines.count(alphabet[i])
		counter[0] += count // 4
		counter[1] += (count % 4) // 2
		counter[2] += count % 2
	return counter

def judge(needs, counter):
	if needs[0] <= counter[0] and needs[2] == counter[2]:
		return "Yes"
	else:
		return "No"


def main():
	nums = list(map(int, input().split()))
	input_lines = "".join([input() for _ in range(nums[0])])
	print(judge(needs(nums[0], nums[1]), alphabetCount(input_lines)))


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
h,w = list(map(int,input().split()))
a = [0] * h
m = [0] * 27
if h == w == 1:
    print('Yes')
    exit()

for i in range(h):
    a[i] = list(input())
    for j in range(w):
        m[ord(a[i][j])-97] += 1
wki = w%2
hki = h%2
whan = int(w/2)
hhan = int(h/2)

m.sort()
m.reverse()

yon = int(whan * hhan)
ni =int(  (wki * hhan) + (hki * whan) )
iti = 0
if wki == 1 and hki == 1:
    iti = 1
flag = 0
for i in range(26):
    if (m[i]%2 == 1 and iti == 0) or (m[i]%2 == 1 and flag == 1):
        print('No')
        exit()
    if m[i]%2 == 1 and flag == 0 and iti == 1:
        flag +=1
        m[i] -= 1
        iti -= 1

for i in range(26):
    while m[i] >=4 and yon > 0:
        m[i] -= 4
        yon -= 1
if yon:
    print('No')
    exit()
m.sort()
m.reverse()
for i in range(26):
    while m[i] >= 2 and ni >0:
        m[i] -= 2
        ni -= 1
if ni :
    print('No')
    exit()

print('Yes')

Submission status: Accepted

Solution code:
H,W = map(int,input().split())

L = [0]*26
for _ in range(H):
  for a in input():
    L[ord(a)-ord('a')] += 1

m2 = 0
m1 = 0
for n in L:
  if n%4 != 0:
    if n%2 == 0:
      m2 += 1
    else:
      m1 += 1

if H%2 == 0 and W%2==0:
  print('Yes' if m1+m2 == 0 else 'No')
elif H%2==0:
  print('Yes' if m1 == 0 and 2*m2 <= H else 'No')
elif W%2==0:
  print('Yes' if m1 == 0 and 2*m2 <= W else 'No')
else:
  print('Yes' if m1 == 1 and 2*m2 < H+W else 'No')

Submission status: Accepted

Solution code:
raw1 = input().split()
H = int(raw1[0])
W = int(raw1[1])

c = [0 for x in range(26)]

for i in range(H):
    raw = input()
    for j in range(W):
        c[ord(raw[j]) - 97] += 1

for i in range(len(c)):
    c[i] = c[i] % 4


if c.count(3) > 0 :
    print('No')
elif W%2 == 1 and H%2 == 1 and c.count(1) == 1 and c.count(2) <= (H-1)/2 +(W-1)/2:
    print('Yes')
elif W%2 == 0 and H%2==0 and c.count(1)==0 and c.count(2) ==0:
    print('Yes')
elif W % 2 ==0 and  H % 2  == 1 and c.count(1) == 0 and c.count(2) <= W/2:
    print('Yes')
elif W % 2 ==1 and  H % 2  == 0 and c.count(1) == 0 and c.count(2) <= H/2:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
from collections import Counter
import numpy as np

hw = input().split()
h = int(hw[0])
w = int(hw[1])

# print(h,w)
a_all = ""
for i in range(h):
    a_all += input()
    
count = Counter(a_all)

four_num = (w//2) * (h//2)
two_num = (w%2) * (h//2) + (h%2) * (w//2)
one_num = (w%2) * (h%2)

# print("test:",four_num,two_num,one_num)
nums = list(count.values())

nums_array = np.array(nums)

check=0

# print(nums_array)
for i in range(four_num):
    if len(nums_array[nums_array>=4])>=1:
        nums_array[np.where(nums_array>=4)[0][0]] -= 4
#         print(nums_array)
    else:
        check = 1
        break

for i in range(two_num):
    if len(nums_array[nums_array>=2])>=1:
        nums_array[np.where(nums_array>=2)[0][0]] -= 2
#         print(nums_array)
    else:
        check = 1
        break

if check == 1:
    print("No")
else:
    print("Yes")

Submission status: Accepted

Solution code:
#Palindromic Matrix
h,w = list(map(int, input().split()))
a = []
for i in range(h):
    a.append(input())
a = "".join(a)

import collections
c = collections.Counter(a).values()
d = 0
e = 0
for ci in c:
    d+=ci//4
    e+=ci//2

#print( (h//2)*(w//2), (h//2)*(w%2)+(w//2)*(h%2))
#print(d, e-2*d)

if (d-(h//2)*(w//2)>=0 and e-2*d+2*(d-(h//2)*(w//2))>=(h//2)*(w%2)+(w//2)*(h%2)):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())

count = {}
for _ in range(H):
    for s in input().strip():
        count[s] = count.get(s, 0) + 1

req = [0] * 4

for h in range(H//2+H%2):
    if h < H // 2:
        c = 2
    else:
        c = 1
    for w in range(W//2+W%2):
        if w < W // 2:
            cc = c * 2
        else:
            cc = c
        req[cc - 1] += 1

for r in [4, 2, 1]:
    for i in range(req[r-1]):
        for s in count:
            if count[s] >= r:
                count[s] -= r
                break
        else:
            print('No')
            exit(0)
print('Yes')

Submission status: Accepted

Solution code:
from collections import defaultdict
h, w =  map(int, raw_input().split())

a = []
aa = ""
for i in xrange(h):
    s = raw_input()
    a.append(s)
    aa += s

d = defaultdict(int)
for c in aa:
    d[c] += 1

q = 0
ch = 0
pair = 0
for cnt in d.values():
    q += cnt / 4
    r = cnt % 4
    if r >= 2:
        pair += 1
        r %= 2
    ch += r

def is_odd(x):
    return x % 2 == 1

if is_odd(h) and is_odd(w):
    if q >= (h/2) * (w/2) and ch == 1:
        print 'Yes'
    else:
        print 'No'
elif not is_odd(h) and not is_odd(w):
    if q >= (h/2) * (w/2) and pair == 0 and ch == 0:
        print 'Yes'
    else:
        print 'No'
else:
    if q >= (h/2) * (w/2) and ch == 0:
        print 'Yes'
    else:
        print 'No'

Submission status: Accepted

Solution code:
from  collections import Counter

if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    a = []
    for i in range(H):
        a.extend(input())

    counter = Counter(a)

    value_divide_by_4 = []
    for i in counter.values():
        value_divide_by_4.append(i % 4)
    # print(value_divide_by_4)

    ans = "Yes"
    cnt_odd = 0
    cnt_even = 0
    if H % 2 == 0 and W % 2 == 0:
        for i in value_divide_by_4:
            if i != 0:
                ans = "No"
                break
    elif H % 2 != 0 and W % 2 != 0:
        # cnt_odd = 0
        # cnt_even = 0
        accept = (H - 1) // 2 + (W - 1) // 2
        for i in value_divide_by_4:
            if i == 1:
                cnt_odd += 1
            elif i == 3:
                cnt_odd += 1
                cnt_even += 1
            elif i == 2:
                cnt_even += 1

            if cnt_odd >= 2:
                ans = "No"
                break
            elif cnt_even > accept:
                ans = "No"
                break
    else:
        if H % 2 == 0:
            accept = H // 2
        else:
            accept = W // 2

        for i in value_divide_by_4:
            if i == 1:
                cnt_odd += 1
            elif i == 3:
                cnt_odd += 1
                cnt_even += 1
            elif i == 2:
                cnt_even += 1

            if cnt_odd >= 2:
                ans = "No"
                break
            elif cnt_even > accept:
                ans = "No"
                break

    print(ans)

Submission status: Accepted

Solution code:
import sys
def solver1( m , h, w):
    for k, v in m.items():
        if v%2 == 1:
            m[k] = m[k] - 1
            break
    _2kcount = (h-1)/2 + (w-1)/2
    _4kcount = ((h-1)/2) * ((w-1)/2 )
    for k, v in m.items():
        if v%4 == 2:
            _2kcount -= 1
            m[k] = m[k] - 2
        elif v%4 != 0:
            return 'No'
    if _2kcount < 0:
        return 'No'
    if _2kcount %2 != 0:
        return 'No'
    return 'Yes'
    #we don't need to care about 4k case because the total amount of material is fix.
def solver2( m, h, w):
    oddc = h if h%2 == 1 else w
    evenc = w if w%2 == 0 else h
    _2kcount = evenc/2
    for k, v in m.items():
        if v%4 == 2:
            _2kcount -= 1
            m[k] = m[k] - 2
        elif v%4 != 0:
            return 'No'
    if _2kcount < 0:
        return 'No'
    if _2kcount %2 != 0:
        return 'No'
    return 'Yes'

H,W = map(int, sys.stdin.readline().strip().split())

matrix = []
materials = {}
for _ in xrange(H):
    line = sys.stdin.readline().strip()
    for a in line:
        materials[a] = materials.get(a, 0) + 1

if H%2 == 0 and W%2 == 0:
    for value in materials.values():
        if value % 4 == 0:
            continue
        else:
            print 'No'
            exit(0)
    print 'Yes'
    exit(0)
if H%2 == 1 and W%2 == 1:
    print solver1(materials, H, W)
    exit(0)

print solver2(materials, H, W)
exit(0)

Submission status: Accepted

Solution code:
from  collections import Counter
H, W = map(int, input().split())
A = []
C = Counter()
for i in range(H):
    A.append(input())
    C += Counter(A[i])

if(H%2 == 0 and W%2 == 0):
    for l in C:
        if(C[l]%4):
            print("No")
            exit()
    print("Yes")
elif(H%2 and W%2):
    t = 0
    for l in C:
        if(C[l]%2):
            t += 1
            C[l] -= 1
    if(t != 1):
        print("No")
        exit()

    t = 0
    for l in C:
        if(C[l]%4):
            t += 1

    if((H+W-2)//2-t >= 0 and ((H+W-2)//2-t)%2 == 0):
        print("Yes")
    else:
        print("No")
else:
    t = 0
    r = H*(W%2) + W*(H%2)
    for l in C:
        if(C[l]%2):
            print("No")
            exit()
        elif(C[l]%4):
            t += 1
    if(r//2-t >= 0 and (r//2-t)%2 == 0):
        print("Yes")
    else:
        print("No")

Submission status: Accepted

Solution code:
H,W = list(map(int,input().split()))
histo = {}
for i in range(H):
    for c in input():
        histo[c] = histo.get(c,0) + 1
ls = [0,0,0]
for v in histo.values():
    ls[0] += v//4
    ls[1] += (v%4)//2
    ls[2] += v%2
ans = [(H//2)*(W//2), (H//2)*(W%2)+(H%2)*(W//2), (H%2)*(W%2)]
a = "No"
if ls[0]>=ans[0]:
    ls[1] += (ls[0]-ans[0])*2
    ls[0] = ans[0]
    if ls==ans:
        a = "Yes"
print(a)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll

def solve():
    H, W = map(int, raw_input().split())
    a = [list(raw_input()) for i in xrange(H)]

    cnt = [0]*26
    for ai in a:
        for c in ai:
            cnt[ord(c) - ord("a")] += 1
    if H%2 == 0 and W%2 == 0:
        for i in xrange(26):
            if cnt[i]%4 != 0:
                return False
        return True
    elif H%2 == 0 or W%2 == 0:
        for i in xrange(26):
            if cnt[i]%2 != 0:
                return False
            cnt[i] /= 2
        X = W/2 if W%2 == 0 else H/2
        odd = sum(cnt[i]%2 != 0 for i in xrange(26)) 
        return odd <= X 
    else:
        odd = sum(cnt[i]%2 != 0 for i in xrange(26)) 
        four = sum(cnt[i]/4 for i in xrange(26))
        return odd == 1 and four >= (H/2)*(W/2)

print "Yes" if solve() else "No"

Submission status: Accepted

Solution code:
n, m = [int(c) for c in input().split(' ')]
mx = [input() for _ in range(n)]

table = [[0] * m for _ in range(n)]
counter = 0
for i in range(n):
    for j in range(m):
        if table[i][j]:
            continue
        counter += 1
        # print("Set {} for ({},{}), ({},{}), ({},{}), ({},{}).".format(
        #     counter, i, j, n-i-1, j, i, m-j-1, n-i-1, m-j-1
        # ))
        table[i][j] = table[n-i-1][j] = table[i][m-j-1] = table[n-i-1][m-j-1] = counter
# print(table)

cnt_need = [0] * counter
cnt_had = [0] * 26
for i in range(n):
    for j in range(m):
        cnt_need[table[i][j]-1] += 1
        cnt_had[ord(mx[i][j]) - ord('a')] += 1

cnt_need.sort()
cnt1, cnt2, cnt4 = [0] * 3
for cnt in cnt_need:
    if cnt == 1:
        cnt1 += 1
    elif cnt == 2:
        cnt2 += 1
    elif cnt == 4:
        cnt4 += 1
    else:
        raise RuntimeError("Unexpected count: {}".format(cnt))
assert cnt1 in [0, 1], "Unexpected count of units: {}".format(cnt1)

possible = 1
for had in cnt_had:
    if had % 2:
        if cnt1 > 0:
            cnt1 -= 1
            had -= 1
        else:
            possible = 0
    if had % 4:
        if cnt2 > 0:
            cnt2 -= 1
            had -= 2
        else:
            possible = 0

print("Yes" if possible else 'No')

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division, print_function
import sys


def main():
    h, w = map(int, sys.stdin.readline().strip().split(" "))
    aa = ""
    for _ in range(h):
        aa += sys.stdin.readline().strip()
    d = {}
    for c in aa:
        if c in d:
            d[c] += 1
        else:
            d[c] = 1

    # print(d)
    fours = 0
    evens = 0
    odds = 0

    for c, count in d.items():
        fours += count // 4
        evens += (count % 4) // 2
        odds += count % 2

    # print(fours, evens, odds)
    if h % 2 == 0 and w % 2 == 0:
        print("Yes" if odds == 0 and evens == 0 else "No")
    elif h % 2 == 0 and w % 2 == 1:
        if odds != 0:
            print("No")
            return
        if 4 * fours < h * (w - 1):
            print("No")
            return
        print("Yes")
    elif h % 2 == 1 and w % 2 == 0:
        if odds != 0:
            print("No")
            return
        if 4 * fours < w * (h - 1):
            print("No")
            return
        print("Yes")
    else:
        if odds != 1:
            print("No")
            return
        if 4 * fours < (w - 1) * (h - 1):
            print("No")
            return
        print("Yes")


if __name__ == '__main__':
    main()